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 保持顺序)

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

相关推荐
RuoyiOffice8 分钟前
达梦 DM8 + openGauss:RuoYi Office 的 MySQL 数据转换与导入实践
数据库·spring boot·python·sql·信创
用户0332126663678 分钟前
轻松使用 Python 将 RTF 转换为 Word 文档(含批量转换与格式互转)
python
Rain的Java大神之路16 分钟前
100 亿条数据如何快速写入 MySQL?从 231 天到 3.5 小时,我把面试官问懵了
java·后端·面试
程序猿乐锅19 分钟前
面向对象练习:图书借阅系统里的封装、抽象类与多态
开发语言·前端·数据库·后端·python·学习·1024程序员节
xyouyuweizhu24 分钟前
Java IO 流详解:流的作用、流的划分与标准输入输出流
java·python·php
lumengabc34 分钟前
视频制作文字转语音PPT台词生成合成合并视频导出ffmpeg软件python edge-tts
python
MSTcheng.37 分钟前
Agent 跑到一半崩了,怎么从上一步接着跑?LangGraph StateGraph 实战:状态持久化、断点恢复与人工审批
python·状态管理·ai agent·langgraph·断点恢复·人工审批
略略略咯咯40 分钟前
33333
开发语言·windows·python
java_prinln41 分钟前
11. 说说 Single-Agent 和 Multi-Agent 的设计方案?
python
垆边人似月.44 分钟前
第三篇:函数、文件与异常处理 / Functions, Files & Exception Handling
开发语言·python