stream表达式常用用法

1.定义一个对象集合,填充一些数据    

        List<Student> stuList = new ArrayList<>();
        stuList.add(new Student(1L, "刘一", 20, "男"));
        stuList.add(new Student(2L, "钱二", 20, "男"));
        stuList.add(new Student(3L, "张三", 10, "男"));
        stuList.add(new Student(4L, "李四", 20, "男"));
        stuList.add(new Student(5L, "王五", 30, "女"));
        stuList.add(new Student(6L, "赵六", 20, "女"));
        stuList.add(new Student(7L, "孙七", 20, "女"));
        stuList.add(new Student(8L, "周八", 20, "男"));
       

2.根据年龄排序
        List<Student> collect = stuList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
        
        System.out.println(collect.toString());
        

3.根据年龄倒序
        List<Student> collect1 = stuList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
        
        System.out.println(collect1.toString());


4.获取年龄最大的对象     
        Student stu = stuList.stream().max(Comparator.comparing(Student::getAge)).get();
        
        System.out.println(stu.getAge());

5.获取年龄大于20岁的对象集合
        
        List<Student> collect2 = stuList.stream().filter(x -> x.getAge() > 20).collect(Collectors.toList());
        
        System.out.println(collect2.toString());

6.获取所有对象的id的集合
        
        List<Long> collect3 = stuList.stream().map(Student::getId).collect(Collectors.toList());
        
        System.out.println(collect3.toString());

7.获取所有对象的年龄倒序的集合
        
        List<Integer> collect4 = stuList.stream().map(Student::getAge).distinct().collect(Collectors.toList());
    
        System.out.println(collect4.toString());

8.获取所有对象年龄的和、平均值等
        
        IntSummaryStatistics collect5 = stuList.stream().collect(Collectors.summarizingInt(Student::getAge));
    
        System.out.println(collect5.getSum()+"-"+collect5.getAverage()+"-"+collect5.getCount());

9.根据年龄分组
    
        Map<Integer, List<Student>> collect6 = stuList.stream().collect(Collectors.groupingBy(Student::getAge));
    
        System.out.println(collect6.keySet().toString());
        
        System.out.println(collect6.get(20));

10.获取所有对象的名字拼接成字符串
        
        String collect7 = stuList.stream().map(Student::getName).collect(Collectors.joining("--"));
        
        System.out.println(collect7);

11.根据年龄和性别分组
        
        Map<Integer, Map<String, List<Student>>> collect8 = stuList.stream().collect(Collectors.groupingBy(Student::getAge,Collectors.groupingBy(Student::getSex)));
        
        for (Integer key : collect8.keySet()) {
            
            System.out.println(collect8.get(key));
        }

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值