欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

strm().filter().collect()和stream().map().collect()的作用

程序员文章站 2022-03-23 22:49:01
在看代码的时候看到了一下...

在看代码的时候看到了相关方法,自己在写了个例子练习一下

public class People {
    private Integer id;
    private String name;
    private Boolean sex;
//省略
}
public class Filter {
    public static void main(String[] args) {
        People people1 = new People(1, "Ligs", true);
        People people2 = new People(2, "Songzx", false);
        People people3 = new People(3, "Jinzg", true);
        People people4 = new People(4, "Liuzx", false);
        People people5 = new People(5, "Hedx", true);
        People people6 = new People(6, "Quansm", false);
        People people7 = new People(7, "Liangsz", true);
        People people8 = new People(8, "Chisz", true);
        ArrayList<People> list = new ArrayList<People>() {{
            add(people1);
            add(people2);
            add(people3);
            add(people4);
            add(people5);
            add(people6);
            add(people7);
            add(people8);
        }};
        System.out.println(list.stream().filter(People::getSex).collect(Collectors.toList()));
        //[People{id=1, name='Ligs', sex=true}, People{id=3, name='Jinzg', sex=true}, People{id=5, name='Hedx', sex=true}, People{id=7, name='Liangsz', sex=true}, People{id=8, name='Chisz', sex=true}]
        //过滤掉sex为false值的对象
        System.out.println(list.stream().map(People::getSex).collect(Collectors.toList()));
        //[true, false, true, false, true, false, true, true]
        //获取list中sex属性的集合
    }
}

本文地址:https://blog.csdn.net/weixin_43898952/article/details/109591164

相关标签: 其他 java