Java8中的Stream操作集合

    1、filter:筛选
        Student stu1 = new Student(1, 19, "张亮");
        Student stu2 = new Student(2, 29, "周文");
        Student stu3 = new Student(3, 23, "王彪");
        List<Student> stuList = new ArrayList<>();
        stuList.add(stu1);
        stuList.add(stu2);
        stuList.add(stu3);
        //筛选年龄大于22岁的学生 
        List<Student> students = stuList
                .stream()
                .filter(student -> student.getAge() > 22)
                .collect(Collectors.toList());
        //结果students:[Student(id=2, age=29, name=周文), Student(id=3, age=23, name=王彪)]
        
    2、map:转换
        Student stu1 = new Student(1, 19, "张亮");
        Student stu2 = new Student(2, 29, "周文");
        Student stu3 = new Student(3, 23, "王彪");
        List<Student> stuList = new ArrayList<>();
        stuList.add(stu1);
        stuList.add(stu2);
        stuList.add(stu3);
        List<String> names = stuList
                    .stream()
                    .map(student -> student.getName())
                    .collect(Collectors.toList());
    //结果names:[张亮, 周文, 王彪]
    
    3、distinct:去重
        Student stu1 = new Student(1, 19, "张亮");
        Student stu2 = new Student(2, 29, "周文");
        Student stu3 = new Student(3, 23, "王彪");
        Student stu4 = new Student(1, 19, "张亮");
        List<Student> stuList = new ArrayList<>();
        stuList.add(stu1);
        stuList.add(stu2);
        stuList.add(stu3);
        List<Student> students = stuList
                .stream()
                .distinct()
                .collect(Collectors.toList());
    //结果students:[Student(id=1, age=19, name=张亮), Student(id=2, age=29, name=周文), Student(id=3, age=23, name=王彪)]
    
    4、anyMatch:Stream 中任意一个元素符合传入的 predicate,返回 true
        Student stu1 = new Student(1, 19, "张亮");
        Student stu2 = new Student(2, 29, "周文");
        Student stu3 = new Student(3, 23, "王彪");
        List<Student> stuList = new ArrayList<>();
        stuList.add(stu1);
        stuList.add(stu2);
        stuList.add(stu3);
        boolean anyMatchFlag = stuList
                .stream()
                .anyMatch(student -> "王彪".equals(student.getName()));
    //结果anyMatchFlag:true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值