目录

1、数据准备:

2、分组

按照类目分组:

按照几个属性拼接分组:

根据不同条件分组

3、多级分组

4、按子组收集数据

求总数

求和

把收集器的结果转换为另一种类型

联合其他收集器


Collectors.groupingBy根据一个或多个属性对集合中的项目进行分组

1、数据准备:

public Product(Long id, Integer num, BigDecimal price, String name, String category) {this.id = id;this.num = num;this.price = price;this.name = name;this.category = category;
}Product prod1 = new Product(1L, 1, new BigDecimal("15.5"), "面包", "零食");
Product prod2 = new Product(2L, 2, new BigDecimal("20"), "饼干", "零食");
Product prod3 = new Product(3L, 3, new BigDecimal("30"), "月饼", "零食");
Product prod4 = new Product(4L, 3, new BigDecimal("10"), "青岛啤酒", "啤酒");
Product prod5 = new Product(5L, 10, new BigDecimal("15"), "百威啤酒", "啤酒");
List<Product> prodList = Lists.newArrayList(prod1, prod2, prod3, prod4, prod5);

2、分组

  • 按照类目分组:

Map<String, List<Product>> prodMap= prodList.stream().collect(Collectors.groupingBy(Product::getCategory));//{"啤酒":[{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10},{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}],"零食":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5},{"category":"零食","id":2,"name":"饼干","num":2,"price":20},{"category":"零食","id":3,"name":"月饼","num":3,"price":30}]}
  • 按照几个属性拼接分组:

Map<String, List<Product>> prodMap = prodList.stream().collect(Collectors.groupingBy(item -> item.getCategory() + "_" + item.getName()));//{"零食_月饼":[{"category":"零食","id":3,"name":"月饼","num":3,"price":30}],"零食_面包":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5}],"啤酒_百威啤酒":[{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}],"啤酒_青岛啤酒":[{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10}],"零食_饼干":[{"category":"零食","id":2,"name":"饼干","num":2,"price":20}]}
  • 根据不同条件分组

Map<String, List<Product>> prodMap= prodList.stream().collect(Collectors.groupingBy(item -> {if(item.getNum() < 3) {return "3";}else {return "other";}
}));//{"other":[{"category":"零食","id":3,"name":"月饼","num":3,"price":30},{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10},{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}],"3":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5},{"category":"零食","id":2,"name":"饼干","num":2,"price":20}]}

3、多级分组

要实现多级分组,我们可以使用一个由双参数版本的Collectors.groupingBy工厂方法创 建的收集器,它除了普通的分类函数之外,还可以接受collector类型的第二个参数。那么要进 行二级分组的话,我们可以把一个内层groupingBy传递给外层groupingBy,并定义一个为流 中项目分类的二级标准。

Map<String, Map<String, List<Product>>> prodMap= prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.groupingBy(item -> {if(item.getNum() < 3) {return "3";}else {return "other";}
})));//{"啤酒":{"other":[{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10},{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}]},"零食":{"other":[{"category":"零食","id":3,"name":"月饼","num":3,"price":30}],"3":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5},{"category":"零食","id":2,"name":"饼干","num":2,"price":20}]}}

4、按子组收集数据

  • 求总数

Map<String, Long> prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));//{"啤酒":2,"零食":3}
  • 求和

Map<String, Integer> prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.summingInt(Product::getNum)));//{"啤酒":13,"零食":6}
  • 把收集器的结果转换为另一种类型

Map<String, Product> prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Product::getNum)), Optional::get)));//{"啤酒":{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15},"零食":{"category":"零食","id":3,"name":"月饼","num":3,"price":30}}
  • 联合其他收集器

Map<String, Set<String>> prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.mapping(Product::getName, Collectors.toSet())));//{"啤酒":["青岛啤酒","百威啤酒"],"零食":["面包","饼干","月饼"]}

5、多层分组

  • Map>>  按用户分组,按类型分组,组装:每个用户、每个类型下的  属性值列表。

Map>> userAttrMap = userAttrList.stream().collect(
                Collectors.groupingBy(IapUserIndustryAttrRel :: getUserId,
                        Collectors.groupingBy(IapUserIndustryAttrRel :: getIndustryTypeId,
                                Collectors.mapping( IapUserIndustryAttrRel :: getIndustryAttributeId, Collectors.toList() )
                                )
                        )
                );

    public static void main(String[] args) {List<IapUserIndustryAttrRel> userAttrList = new ArrayList<>();IapUserIndustryAttrRel userAttr1 = new IapUserIndustryAttrRel();userAttr1.setUserId("100001");userAttr1.setIndustryTypeId("1");userAttr1.setIndustryAttributeId("1");userAttrList.add(userAttr1);IapUserIndustryAttrRel userAttr2 = new IapUserIndustryAttrRel();userAttr2.setUserId("100001");userAttr2.setIndustryTypeId("1");userAttr2.setIndustryAttributeId("2");userAttrList.add(userAttr2);IapUserIndustryAttrRel userAttr3 = new IapUserIndustryAttrRel();userAttr3.setUserId("100001");userAttr3.setIndustryTypeId("2");userAttr3.setIndustryAttributeId("3");userAttrList.add(userAttr3);Map<String, Map<String, List<String>>> userAttrMap = userAttrList.stream().collect(Collectors.groupingBy(IapUserIndustryAttrRel :: getUserId,Collectors.groupingBy(IapUserIndustryAttrRel :: getIndustryTypeId,Collectors.mapping(IapUserIndustryAttrRel :: getIndustryAttributeId, Collectors.toList()))));System.out.println(userAttrMap);}

输出结果:

{100001={1=[1, 2], 2=[3]}}

  • Map>> 按机构号分组,按渠道号分组,组装:每个机构、每个渠道下的  产品信息(map)。
        Test t1= new Test("001","1","Y1","1");Test t2= new Test("001","2","Y1","2");Test t3= new Test("002","1","Y1","3");Test t4= new Test("002","2","Y1","4");Test t5= new Test("001","1","Y2","5");Test t6= new Test("002","1","Y2","6");List<Test> list = new ArrayList<>();list.add(t1);list.add(t2);list.add(t3);list.add(t4);list.add(t5);list.add(t6);Map<String, Map<String, Map<String, String>>> collect = list.stream().collect(Collectors.groupingBy(Test::getOrgCode, Collectors.groupingBy(Test::getChannelId, Collectors.toMap(Test::getProductCode, Test::getD))));System.out.println(JSON.toJSON(collect));

输出结果:

{"001":{"1":{"Y1":"1","Y2":"5"},"2":{"Y1":"2"}},"002":{"1":{"Y1":"3","Y2":"6"},"2":{"Y1":"4"}}}

相关链接:
java8中map新增方法详解
java8中Stream的使用
java8中Collection新增方法详解
java8中Collectors的方法使用实例
java8中常用函数式接口
java8中的方法引用和构造函数引用
java8中的Collectors.groupingBy用法
java8中的Optional用法
java8中的日期和时间API

java8中 Collectors.groupingBy用法相关推荐

  1. java8中的Collectors.groupingBy用法

    Collectors.groupingBy根据一个或多个属性对集合中的项目进行分组 数据准备: public Product(Long id, Integer num, BigDecimal pric ...

  2. java stream中Collectors的用法

    文章目录 简介 Collectors.toList() Collectors.toSet() Collectors.toCollection() Collectors.toMap() Collecto ...

  3. java8中的Stream流式操作总结,List转Map或List转LinkedHashMap使用Collectors.groupingBy用法

    前言背景描述: 开发使用本来是直接使用数据库的依据SQL进行group By获取到数据表的分组的一个字段的字符串,可是后来字符串越来越多越长,导致的最后的后面长度超多1024个汉字就会被截取,所以需要 ...

  4. js 中转换成list集合_java stream中Collectors的用法

    简介 在java stream中,我们通常需要将处理后的stream转换成集合类,这个时候就需要用到stream.collect方法.collect方法需要传入一个Collector类型,要实现Col ...

  5. Java8中Collectors详解

    文章目录 1.averagingDouble 2.collectingAndThen 3.counting 4.groupingBy 4.1groupingBy(Function) 4.2groupi ...

  6. Java8中Collectors的使用

    前言: 基本类型的流没有这个用法 文章目录 averagingDouble,averagingInt,averagingLong collectingAndThen counting grouping ...

  7. java8中的Stream用法详解

    项目github地址:bitcarmanlee easy-algorithm-interview-and-practice 欢迎大家star,留言,一起学习进步 1.为什么java8中加入Stream ...

  8. Java 8中Collectors.groupingBy方法空指针异常源码分析

    现在有这样的一个需求:老板让把所有的员工按年龄进行分组,然后统计各个年龄的人数. 这个需求,如果是在数据库中,可以直接使用一个 group by 语句进行统计即可,那么在 Java 中的话,可以借助于 ...

  9. Java8 Stream Collectors groupingBy使用

    分组List并显示其总数. @Test public void test8() {//3 apple, 2 banana, others 1List<String> items =Arra ...

最新文章

  1. 加速!上海要做人工智能产业“领头雁”
  2. 得到windows系统图标的解决方案(转)
  3. 部署Awstats日志分析系统
  4. linux下netty接收不到服务,Netty 发送消息失败或者接收消息失败的可能原因
  5. 在气候灾难的时代,这些游戏正在用自己的方式去重新审视自然
  6. 前端知识点总结---面试专用
  7. linux里hba状态_Windows和Linux系统查看HBA卡wwn号的方法 | 系统之家官网
  8. php重定向mysql_使用.php文件生成MySQL转储
  9. bzoj 1618: [Usaco2008 Nov]Buying Hay 购买干草(完全背包)
  10. maven的网易镜像
  11. CentOS7.5安装WPS并解决字体报错
  12. 2019 强网杯 babybank
  13. 戴尔r410服务器虚拟磁盘,DELL服务器R410原装 SAS 6/IR RAID卡 阵列控制器卡 支持RAID0,1...
  14. Excel如何简单快速的建立二级下拉菜单?
  15. liuyubobobo:学习方法分享
  16. Educational Codeforces Round 62 (Rated for Div. 2) E. Palindrome-less Arrays(DP+瞎搞)
  17. 转换pdf 为 png
  18. one 主格 复数 宾格_主格和宾格
  19. 领航优配|累计分红超300亿元,外资持续加仓,云计算龙头再拉涨停
  20. C/C++语言ODBC连接SqlServer数据库

热门文章

  1. 第三方登录之QQ登录集成(二)
  2. 基于OpenPose的坐姿识别
  3. 人力资源知识图谱搭建及应用
  4. 新团队团队融合研讨会_行程报告:2020年软件开发人员多样性与融合研讨会
  5. MRS IoTDB时序数据库的总体架构设计与实现
  6. 【手机投影】安卓手机投影到WIN10
  7. 音频和视频的基础知识
  8. android socket 推送服务版本
  9. 【计算机视觉】双目测距(二)--双目标定与矫正
  10. mysql count(*)使用索引和成本计算