使用java8的Stream,根据Object某些属性对List进行筛选。

对对象集合进行处理时,整天for循环筛选,感觉跟不上时代。搜了搜,学了学java8的Stream,并用来替代for循环筛选。

public class StreamTest {

    public static void main (String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2"),
                new Person("e5", "l3"),
                new Person("e6", "l3"),
                new Person("e7", "l3")

        );
        //.filter(过滤条件)
        //.collect(Collectors.toList()) 把结果搜集到List之中。
        persons = persons.stream().filter(person -> person.getLastName().equals("l3")).collect(Collectors.toList());
        persons.forEach(person -> {
            System.out.println(person.getName());
        });


    }
}

public class Person {


    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

结果:

e5
e6
e7

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