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

如何使用Java Stream API将Employee列表转换为Set值的Map

如何用Java Stream API将Employee列表转换为指定结构的Map?

当然可以!用Java Stream API完全能轻松实现这个需求,我来给你一步步拆解怎么做:

首先先确认我们的基础代码(也就是你给出的Employee类和列表初始化):

class Employee {
    private String praefix;
    private String middleFix;
    private String postfix;
    private String name;

    public Employee(String praefix, String middleFix, String postfix, String name) {
        this.praefix = praefix;
        this.middleFix = middleFix;
        this.postfix = postfix;
        this.name = name;
    }

    public String getPraefix() { return praefix; }
    public void setPraefix(String praefix) { this.praefix = praefix; }
    public String getMiddleFix() { return middleFix; }
    public void setMiddleFix(String middleFix) { this.middleFix = middleFix; }
    public String getPostfix() { return postfix; }
    public void setPostfix(String postfix) { this.postfix = postfix; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

// 初始化员工列表
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("A", "B", "C", "Michael Phelps"));
employees.add(new Employee("A", "B", "C", "Cristiano Ronaldo"));
employees.add(new Employee("D", "E", "F", "Usain Bolton"));
employees.add(new Employee("D", "E", "F", "Diego Armando Maradona"));
employees.add(new Employee("D", "E", "F", "Lionel Messi"));

接下来就是核心的Stream处理代码,直接生成你想要的Map结构:

Map<String, List<String>> employeeMap = employees.stream()
    .collect(Collectors.groupingBy(
        // 生成分组的键:拼接praefix、middleFix、postfix为"X.Y.Z"格式
        emp -> String.join(".", emp.getPraefix(), emp.getMiddleFix(), emp.getPostfix()),
        // 下游收集器:先把Employee映射为name,再收集并排序
        Collectors.mapping(
            Employee::getName,
            Collectors.collectingAndThen(
                Collectors.toList(),
                nameList -> {
                    // 对名字列表按自然字母顺序排序
                    nameList.sort(String::compareTo);
                    return nameList;
                }
            )
        )
    ));

代码解释:

  • 分组键生成:用String.join(".", ...)把三个前缀字段拼接成你需要的"前缀.中间缀.后缀"格式,作为Map的key。
  • 映射与排序:通过Collectors.mapping把每个Employee对象转换为对应的name字符串;再用Collectors.collectingAndThen先把名字收集成List,紧接着对List进行自然排序(对应你示例里的字母顺序排列)。

运行这段代码后,得到的employeeMap结构就完全符合你的要求:

{A.B.C=[Cristiano Ronaldo, Michael Phelps], D.E.F=[Diego Armando Maradona, Lionel Messi, Usain Bolton]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:05:37