java如何分组
分组方法概述
在Java中,分组操作通常涉及将集合中的元素按照特定条件分类。常见的实现方式包括使用Stream API、Collectors.groupingBy()或手动遍历处理。以下是几种典型场景的实现方法。
使用Stream API分组
通过Collectors.groupingBy()可以快速实现分组。假设有一个List<Person>需要按年龄分组:
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25)
);
Map<Integer, List<Person>> groupedByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// 输出: {25=[Alice, Charlie], 30=[Bob]}
多级分组
支持嵌套分组条件,例如先按年龄再按姓名长度分组:
Map<Integer, Map<Integer, List<Person>>> multiLevelGroup = people.stream()
.collect(Collectors.groupingBy(
Person::getAge,
Collectors.groupingBy(p -> p.getName().length())
));
自定义分组逻辑
通过Lambda表达式或方法引用定义分组规则。例如按奇偶年龄分组:
Map<String, List<Person>> oddEvenGroup = people.stream()
.collect(Collectors.groupingBy(
p -> p.getAge() % 2 == 0 ? "Even" : "Odd"
));
手动遍历实现分组
若不使用Stream,可通过遍历集合手动构建分组映射:
Map<Integer, List<Person>> manualGroup = new HashMap<>();
for (Person person : people) {
manualGroup.computeIfAbsent(person.getAge(), k -> new ArrayList<>())
.add(person);
}
分组后处理
分组后可对结果进一步操作,例如统计每组的数量:

Map<Integer, Long> countByAge = people.stream()
.collect(Collectors.groupingBy(
Person::getAge,
Collectors.counting()
));
注意事项
- 分组键为
null时,默认归类到HashMap的null键中。 - 线程安全场景需使用
ConcurrentHashMap或同步处理。 - 大数据量分组时,考虑并行流(
.parallelStream())提升性能。
以上方法覆盖了从简单到复杂的分组需求,根据具体场景选择合适实现即可。






