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 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 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 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);
}
}

你可能感兴趣的:(jdk1.8)