大家看一下下面的案例:
//下面是初始化的数据 List<Student> list = new ArrayList<Student>(); Student student1 = new Student("李四1", "女", "一班"); Student student2 = new Student("李四2", "女", "一班"); Student student3 = new Student("李四3", "女", "一班"); Student student4 = new Student("李四4", "男", "一班"); Student student5 = new Student("李四5", "男", "一班"); Student student6 = new Student("李四6", "男", "二班"); Student student7 = new Student("李四7", "男", "二班"); Student student8 = new Student("李四8", "男", "二班"); Student student9 = new Student("李四9", "男", "二班"); list.add(student1); list.add(student2); list.add(student3); list.add(student4); list.add(student5); list.add(student6); list.add(student7); list.add(student8); list.add(student9);
1.合理利用map操作
在实际开发中合理的利用map自带的方法,能解决很多问题
for (Student stu : list) { if (!map.containsKey(stu.getProvinceCode())) { ArrayList<ArrearageDeal> al = new ArrayList<ArrearageDeal>(); map.put(stu.getProvinceCode(), al.add(stu)); } else { map.get(stu.getProvinceCode()).add(stu); } }
2.利用guava的Multimap
Multimap<String, Student> mulMap = ArrayListMultimap.create(); for (Student stu : list) { mulMap.put(stu.getGrade,stu); }
3.使用jdk8新特性–不要排斥新东西
毕竟java14都出来了,java8的新特性还是需要多了解
//一行就可以解决 Map<String, List<Student >> collect = list.stream().collect(Collectors.groupingBy(ArrearageDeal::getGrade));
上面三种当时从代码量上来看,java8的最简洁。但是实际开发中结合具体场景来说2、3两种都是不错的选择。
Java8 多个字段分组统计
// 分组统计 Map<String, Long> countMap = records.stream().collect(Collectors.groupingBy(o -> o.getProductType() + "_" + o.getCountry(), Collectors.counting())); List<Record> countRecords = countMap.keySet().stream().map(key -> { String[] temp = key.split("_"); String productType = temp[0]; String country = temp[1]; Record record = new Record(); record.set("device_type", productType); record.set("location", country; record.set("count", countMap.get(key).intValue()); return record; }).collect(Collectors.toList());
以上是java分组统计功能如何实现的详细内容。更多信息请关注PHP中文网其他相关文章!
声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除

Go语言实现国密SM4和SM2加解密本文将详细介绍如何使用Go语言实现国密SM4和SM2算法的加解密流程,以满足与Java应�...

在Python项目中是否需要分层?最近我在学习Python时,注意到Django开源项目中,很多都在views函数里编写了大量的�...

系统对接中的字段映射处理在进行系统对接时,常常会遇到一个棘手的问题:如何将A系统的接口字段有效地映�...

IntelliJIDEA如何识别SpringBoot项目的端口号?在使用IntelliJIDEAUltimate版本启动Spring...

关于JWT和Session的困惑与解答许多初学者在学习JWT和Session时,常常会对其本质和适用场景感到困惑。本文将围绕J...

WindowsServer2019防火墙与WebSocket通信问题详解在使用SpringBoot开发的Jar程序部署于WindowsServer2019...


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章
刺客信条阴影:贝壳谜语解决方案
3 周前ByDDD
Windows 11 KB5054979中的新功能以及如何解决更新问题
2 周前ByDDD
在哪里可以找到原子中的起重机控制钥匙卡
3 周前ByDDD
节省R.E.P.O.解释(并保存文件)
1 个月前By尊渡假赌尊渡假赌尊渡假赌
刺客信条阴影 - 如何找到铁匠,解锁武器和装甲定制
4 周前ByDDD

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Dreamweaver Mac版
视觉化网页开发工具

WebStorm Mac版
好用的JavaScript开发工具

禅工作室 13.0.1
功能强大的PHP集成开发环境