java8 stream 中Collectors使用详解

文章展示了如何使用Java集合流(Stream)进行数据处理,包括创建测试数据、获取对象属性集合、转换为Map、求和、最大值、平均值计算、去重、分组以及按照特定条件分区等操作。通过这些方法,可以高效地对数据进行分析和处理。
摘要由CSDN通过智能技术生成

一.首先先造点我们用来测试的数据

        Student student=new Student("001","sgh",99,"men");
        Student student1=new Student("002","asd",100,"women");
        Student student2=new Student("003","dfg",110,"men");
        Student student3=new Student("004","erg",115,"men");
         List<Student> studentList=new ArrayList<Student>();
        studentList.add(student);
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);

二、获得对象中某1个属性集合

List<Integer> scoreList= studentList.stream().map(Student::getScore).collect(Collectors.toList());

三、list转换为map集合

toMap 将List的值转成 stuNo -> name的Map

Map<String,String> studentMap= studentList.stream().collect(Collectors.toMap(Student::getStuNo,Student::getName));

四、求和、最大值、平均值

求socre最大的对象

Optional<Student> student4= studentList.stream().filter(s -> s.getScore() != null).max(Comparator.comparing(Student::getScore));

求socre的和

Integer socreSum=studentList.stream().mapToInt(Student::getScore).sum();

求平均值

Double averageSocre= studentList.stream().collect(Collectors.averagingDouble(Student::getScore));

五、去重

对数据去重

 studentList.stream().distinct().collect(Collectors.toList());

根据某一属性去重

studentList.stream().collect(collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));

六、分组

按照性别分组并且统计数量

Map<String,Long> stringListMap=studentList.stream().collect(Collectors.groupingBy(Student::getSex,Collectors.counting()));

分组后在比较,求分组中socre最小的

 Map<String,Student> stringStudentMap=studentList.stream()
                .collect(Collectors.groupingBy(Student::getSex,Collectors.collectingAndThen(Collectors.minBy(Comparator.comparing(Student::getScore)),Optional::get)));

7.partitioningBy分区

按照socre>100分区,在统计

Map<Boolean,Long> booleanLongMap= studentList.stream().collect(Collectors.partitioningBy(s->s.getScore()>100,Collectors.counting()));

partitioningBy与groupingBy区别
在这里插入图片描述
partitioningBy函数的参数一个Predicate接口,那么这个接口的返回值是boolean类型的,也只能是boolean类型,然后他的返回值是Map的key是boolean类型,也就是这个函数的返回值只能将数据分为两组也就是ture和false两组数据。
在这里插入图片描述
groupingBy的函数参数为Function然后他的返回值也是Map,但是他的key是泛型,那么这个分组就会将数据分组成多个key的形式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值