news 2026/7/2 14:49:17

java list怎么进行group

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
java list怎么进行group

在Java中,对List进行分组有多种方法,以下是常见的几种方式:

1. 使用 Stream API (Java 8+ 推荐)

1.1 按属性分组

// 按对象属性分组 List<Person> people = Arrays.asList( new Person("Alice", "IT"), new Person("Bob", "HR"), new Person("Charlie", "IT") ); Map<String, List<Person>> byDept = people.stream() .collect(Collectors.groupingBy(Person::getDepartment)); // 复杂分组:按多个条件分组 Map<String, Map<Integer, List<Person>>> byDeptAndAge = people.stream() .collect(Collectors.groupingBy( Person::getDepartment, Collectors.groupingBy(Person::getAge) ));

1.2 分组后处理

// 分组并计数 Map<String, Long> countByDept = people.stream() .collect(Collectors.groupingBy( Person::getDepartment, Collectors.counting() )); // 分组并求和 Map<String, Integer> sumByDept = people.stream() .collect(Collectors.groupingBy( Person::getDepartment, Collectors.summingInt(Person::getSalary) )); // 分组后获取最大/最小值 Map<String, Optional<Person>> maxByDept = people.stream() .collect(Collectors.groupingBy( Person::getDepartment, Collectors.maxBy(Comparator.comparing(Person::getSalary)) ));

2. 使用传统循环

Map<String, List<Person>> byDept = new HashMap<>(); for (Person person : people) { String dept = person.getDepartment(); byDept.computeIfAbsent(dept, k -> new ArrayList<>()) .add(person); }

3. 使用第三方库

3.1 Apache Commons Collections

// 添加依赖 // implementation 'org.apache.commons:commons-collections4:4.4' MultiValuedMap<String, Person> byDept = new ArrayListValuedHashMap<>(); for (Person person : people) { byDept.put(person.getDepartment(), person); }

3.2 Google Guava

// 添加依赖 // implementation 'com.google.guava:guava:31.1-jre' Multimap<String, Person> byDept = ArrayListMultimap.create(); for (Person person : people) { byDept.put(person.getDepartment(), person); } // 或者使用流式方式 ImmutableListMultimap<String, Person> grouped = Multimaps.index( people, Person::getDepartment );

4. 完整示例

import java.util.*; import java.util.stream.Collectors; class Person { private String name; private String department; private int age; private int salary; // 构造方法、getter、setter public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("Alice", "IT", 25, 5000), new Person("Bob", "HR", 30, 4500), new Person("Charlie", "IT", 28, 5500), new Person("David", "HR", 35, 4800) ); // 1. 按部门分组 Map<String, List<Person>> byDept = people.stream() .collect(Collectors.groupingBy(Person::getDepartment)); // 2. 按部门统计平均工资 Map<String, Double> avgSalaryByDept = people.stream() .collect(Collectors.groupingBy( Person::getDepartment, Collectors.averagingDouble(Person::getSalary) )); // 3. 按年龄段分组 Map<String, List<Person>> byAgeGroup = people.stream() .collect(Collectors.groupingBy(p -> { if (p.getAge() < 30) return "青年"; else if (p.getAge() < 40) return "中年"; else return "资深"; })); } }

5. 自定义分组逻辑

// 自定义分组器 Collector<Person, ?, Map<String, List<Person>>> customGrouping = Collector.of( HashMap::new, // 供应者 (map, person) -> { // 累加器 String key = person.getDepartment() + "-" + (person.getAge() / 10 * 10); // 按10岁分段 map.computeIfAbsent(key, k -> new ArrayList<>()) .add(person); }, (map1, map2) -> { // 合并器(用于并行流) map2.forEach((key, value) -> map1.merge(key, value, (list1, list2) -> { list1.addAll(list2); return list1; }) ); return map1; } ); Map<String, List<Person>> customGrouped = people.stream() .collect(customGrouping);

选择建议:

  1. Java 8+:优先使用Stream API+Collectors.groupingBy(),代码简洁高效

  2. 复杂分组:使用多级分组或自定义分组逻辑

  3. 并行处理:考虑使用并行流parallelStream()

  4. 性能考虑:大数据量时注意选择合适的 Map 实现(如 LinkedHashMap 保持顺序)

这些方法可以根据具体需求灵活选择和使用。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/24 23:11:03

BlenderKit实战宝典:3D创作效率倍增的秘诀

BlenderKit实战宝典&#xff1a;3D创作效率倍增的秘诀 【免费下载链接】BlenderKit Official BlenderKit add-on for Blender 3D. Documentation: https://github.com/BlenderKit/blenderkit/wiki 项目地址: https://gitcode.com/gh_mirrors/bl/BlenderKit 还在为寻找合…

作者头像 李华
网站建设 2026/7/2 8:42:17

革命性突破:零基础掌握SD-PPP实现Photoshop与AI绘图的无缝融合

革命性突破&#xff1a;零基础掌握SD-PPP实现Photoshop与AI绘图的无缝融合 【免费下载链接】sd-ppp Getting/sending picture from/to Photoshop in ComfyUI or SD 项目地址: https://gitcode.com/gh_mirrors/sd/sd-ppp 还在为Photoshop与AI工具之间的频繁切换而烦恼吗&…

作者头像 李华
网站建设 2026/6/25 23:20:59

springboot基于vue的一鸣企业员工人事考勤工资管理系统的设计与实现_cg88z7k0

目录已开发项目效果实现截图开发技术介绍核心代码参考示例1.建立用户稀疏矩阵&#xff0c;用于用户相似度计算【相似度矩阵】2.计算目标用户与其他用户的相似度系统测试总结源码文档获取/同行可拿货,招校园代理 &#xff1a;文章底部获取博主联系方式&#xff01;已开发项目效果…

作者头像 李华
网站建设 2026/7/1 19:22:05

NSC_BUILDER终极指南:掌握Switch文件管理的全能工具

NSC_BUILDER&#xff08;Nintendo Switch Cleaner and Builder&#xff09;是一款专为Switch玩家设计的全能文件管理工具&#xff0c;被誉为"Switch玩家的多功能工具"。这款开源工具集成了超过30种实用功能&#xff0c;从基本的文件格式转换到复杂的批量处理操作&…

作者头像 李华
网站建设 2026/6/26 17:31:14

springboot基于vue的动漫服装租赁妆造服务平台的设计与实践 _8a6262a0

目录已开发项目效果实现截图开发技术介绍核心代码参考示例1.建立用户稀疏矩阵&#xff0c;用于用户相似度计算【相似度矩阵】2.计算目标用户与其他用户的相似度系统测试总结源码文档获取/同行可拿货,招校园代理 &#xff1a;文章底部获取博主联系方式&#xff01;已开发项目效果…

作者头像 李华