You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java将Employee列表转为双层Map的高效简洁实现方案问询

优化多级分组与排序的实现方案

我们有如下员工数据表:

id | name | department | sub_department |
-----------------------------------------
1  | emp1 | Finance    | finance_asia   | 
2  | emp2 | Finance    | finance_emea   |
3  | emp3 | Retail     | retail_us      |
4  | emp4 | Investment | inv_africa     |
5  | emp5 | Investment | inv_aus        |

在Spring Boot项目中,通过JPA仓库获取数据:

List<Employee> empList = empRepo.findAll();

Employee类包含String类型的id、name、department和sub_department属性。我们需要构建一个Map<String, Map<String, List<Employee>>>,要求:

  • 外层Map的键为department
  • 内层Map的键为sub_department
  • 对应值为按name排序的Employee列表

原传统实现代码:

Map<String, Map<String, List<Employee>>> departmentMap = new HashMap<>();
var empList = empRepo.findAll();
empList.stream().forEach(emp -> {
   if (departmentMap.get(emp.getDepartment()) == null) {
       departmentMap.put(emp.getDepartment(), new HashMap<String, List<Employee>>());
   }
   if (departmentMap.get(emp.getDepartment()).get(emp.getSubDepartment()) == null) {
       departmentMap.get(emp.getDepartment()).put(emp.getSubDepartment(), new ArrayList<Employee>());   
   }
   departmentMap.get(emp.getDepartment()).get(emp.getSubDepartment()).add(emp);
});

优化实现方案

利用Java Stream的Collectors.groupingBy可以实现更简洁高效的多级分组,同时结合排序逻辑完成需求:

方案一:流式排序转换

List<Employee> empList = empRepo.findAll();

Map<String, Map<String, List<Employee>>> departmentMap = empList.stream()
    // 按department做外层分组
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        // 按sub_department做内层分组
        Collectors.groupingBy(
            Employee::getSubDepartment,
            // 收集列表后按name排序
            Collectors.collectingAndThen(
                Collectors.toList(),
                list -> list.stream()
                    .sorted(Comparator.comparing(Employee::getName))
                    .collect(Collectors.toList())
            )
        )
    ));

方案二:使用有序集合收集

如果允许依赖有序集合来保证排序,可直接在收集阶段完成排序,避免二次流处理:

Map<String, Map<String, List<Employee>>> departmentMap = empList.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.groupingBy(
            Employee::getSubDepartment,
            // 用TreeSet按name排序后转为ArrayList
            Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Employee::getName))),
                ArrayList::new
            )
        )
    ));

方案优势

  • 代码更简洁,逻辑层级清晰,无需手动判断Map和List的初始化
  • 利用JDK内置收集器实现,性能稳定且符合函数式编程风格
  • 排序逻辑与分组逻辑解耦,易于维护和修改

内容的提问来源于stack exchange,提问作者Lolly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:46:22