java8中 Collectors.groupingBy用法

java8中 Collectors.groupingBy用法Collectors.groupingBy根据一个或多个属性对集合中的项目进行分组1、数据准备:publicProduct(Longid,Integernum,BigDecimalprice,Stringname,Stringcategory){this.id=id;this.num=num;this.price=price;this.name=name;this.category=category;}…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

目录

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
 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/171350.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Java集合汇总篇「建议收藏」

    Java集合汇总篇「建议收藏」一.集合框架Java集合框架一些列的接口和类来实现很多常见的数据结构和算法,例如LinkedList就是集合框架提供的实现了双向链表的数据结构,关于这一篇文章建议大家收藏,我会不断地完善和扩充它的内容,例如最下面的系列文章我以后也会对它进行不断的更新集合框架的接口集合框架提供了很多接口,这些接口都包含了特定的方法来实现对集合上的特定操作)我们将要学习这些接口以及子接口和它们的各种实现类,在开始之前我们先简单学习一下这些广泛运用的接口,可以看到整个集合框架,总共有三个顶级接口Collecti

    2022年7月16日
    16
  • 本工作站与主域失去信任_电脑加域后无管理员

    本工作站与主域失去信任_电脑加域后无管理员1.如图。解决方式原因:用户和域的安全通道损坏。解决方式:方式1:退域加域名。(需要重启两次麻烦)方式2:推荐方式:用本地管理员进去。用命令修复安全通道。(使用powershell输入命令打开)(不需要重启)Test-ComputerSecureChannel-Credential域账号(域名\账号)-Repair注意:在本地管理管理员,多尝试几次就能修复了。修复的标志:命令:Test-ComputerSecureChannel造成退域的原因:(不止这几点)1.密码更新失败

    2022年10月19日
    5
  • OPC协议_opc通讯协议简介

    OPC协议_opc通讯协议简介一、OPC:OPC是一种利用微软的COM/DCOM技术来达成自动化控制的协定,采用典型的C/S模式,针对硬件设备的驱动程序由硬件厂商完成,提供统一OPC接口标准的Server程序,软件厂商只需按照OPC标准接口编写Client程序就访问Server程序进行读写,即可实现与硬件设备的通信。OPC协定包括:1.DA(DataAccess)规范:访问数据主要采用该规范2.A&amp;E(Alarma…

    2025年8月23日
    5
  • NB-IoT:指定频点操作「建议收藏」

    NB-IoT:指定频点操作「建议收藏」NBIOT指定频点后需要关闭射频开关,然后再清频点再开射频开关,最后附着网络。实际使用中最好不要锁定频点,否则很容易造成连接不上。AT+NEARFCN=0,2508,123——这里取值均为例子AT+CFUN=0AT+NCSEARFCNAT+CFUN=1AT+CGATT=1先设置频点,然后再清除频点,然后在CGATT…

    2022年10月6日
    2
  • 【灯哥开源四足机器人】推荐一个开源四足机器狗项目,8自有度,两个舵机控制一个腿,apache开源协议的,已经迭代了好多个版本了,设计的非常好。有官方淘宝店,没有3D打印机的可以购买散装零件自己组装[通俗易懂]

    【灯哥开源四足机器人】推荐一个开源四足机器狗项目,8自有度,两个舵机控制一个腿,apache开源协议的,已经迭代了好多个版本了,设计的非常好。有官方淘宝店,没有3D打印机的可以购买散装零件自己组装[通俗易懂]目录前言1,关于【灯哥开源四足机器人】2,使用py-apple3,总结前言本文的原文连接是:https://blog.csdn.net/freewebsys/article/details/108971807未经博主允许不得转载。博主地址是:http://blog.csdn.net/freewebsys1,关于【灯哥开源四足机器人】灯哥开源的四足机器人(不是我)。作者的主页:https://www.bilibili.com/video/BV1Ka4y1t7CLgithub首页:h

    2022年6月9日
    69

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号