栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

java8 stream 中Collectors使用详解

Java 更新时间:发布时间: 百科书网 趣学号

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

        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 studentList=new ArrayList();
        studentList.add(student);
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);

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

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

三、list转换为map集合
toMap 将List的值转成 stuNo -> name的Map

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

四、求和、最大值、平均值
求socre最大的对象

Optional 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(toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));

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

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

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

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

7.partitioningBy分区
按照socre>100分区,在统计

Map 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的形式。

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/273894.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号