java分组统计功能如何实现
作者:OpenWorld
时间:2023-04-25
来源:互联网
浏览:0
大家看一下下面的案例://下面是初始化的数据Listlist=newArrayList();Studentstudent1=newStudent("李四1","女","一班");Studentstudent2=newStudent("李四2","女","一班");Studentstudent3=newStudent("李四3","女","一班");Studentstudent4=newStudent("李四4","男","一班");Studentstudent5=newStudent("李四5","男",
大家看一下下面的案例:
//下面是初始化的数据 Listlist = new ArrayList (); 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 al = new ArrayList();
map.put(stu.getProvinceCode(), al.add(stu));
} else {
map.get(stu.getProvinceCode()).add(stu);
}
} 2.利用guava的Multimap
MultimapmulMap = ArrayListMultimap.create(); for (Student stu : list) { mulMap.put(stu.getGrade,stu); }
3.使用jdk8新特性–不要排斥新东西
毕竟java14都出来了,java8的新特性还是需要多了解
//一行就可以解决 Map> collect = list.stream().collect(Collectors.groupingBy(ArrearageDeal::getGrade));
上面三种当时从代码量上来看,java8的最简洁。但是实际开发中结合具体场景来说2、3两种都是不错的选择。
Java8 多个字段分组统计
// 分组统计 MapcountMap = records.stream().collect(Collectors.groupingBy(o -> o.getProductType() + "_" + o.getCountry(), Collectors.counting())); List 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());
作者最新文章
三星 Galaxy A08 渲染图曝光:Helio G99 芯片与 6000mAh 电池配置解析
2026-09-08 17:14
OPPO Find X10 Pro Max 影像规格详解:三颗2亿像素镜头与全焦段8K视频能力
2026-09-08 16:41
PDF转HTML在线转换器怎么选?转换后网页排版怎么查?
2026-09-04 11:02
AE教程书籍挑选指南:零基础、动效与合成方向实战标准
2026-09-02 13:31
教程书籍使用SAI软件Logo要单独授权吗:商标引用与出版合规要点
2026-09-02 11:50
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















