jdk1.8中的filter应用

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

public class Filter {

public static void main(String[] args) {

        List<String> lines = Arrays.asList(“spring”, “node”, “mkyong”,”mkyong”);

        System.out.println(lines);

        //从集合中获得元素

        String item = lines.stream().filter(line-> “mkyong”.equals(line)).findAny().orElse(null);

        System.out.println(item);

        //从集合中获取集合

        List<String> list = lines.stream().filter(line-> !”mkyong”.equals(line)).collect(Collectors.toList());

        list.forEach(System.out::println);  

        //从对象类中获得元素

        class Person{

       
private String name;

       
private Integer age;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

public Person(String name, Integer age) {

super();

this.name = name;

this.age = age;

}

        }

        List<Person> persons = Arrays.asList(new Person(“mkyong”, 20),new Person(“michael”, 21), new Person(“lawrence”, 23));

   
Integer age = persons.stream().filter(x -> “michael”.equals(x.getName())).map(Person::getAge).findAny().orElse(Integer.valueOf(0));

   
System.out.println(age);

}

}

    原文作者:谁的大王
    原文地址: https://blog.csdn.net/sprita1/article/details/59084549
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞