Java Stream API:如何转换为Set的Map

3
假设我有一个名为Employee的类以及一个包含这些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"));

使用Java Stream-API将其转换为以下地图是否可能?
{A.B.C=[Cristiano Ronaldo, Michael Phelps], D.E.F=[Aydin Korkmaz, Diego Armando Maradona, Usain Bolton]} 
2个回答

6
  Map<String, List<String>> result = employees.stream()
            .collect(Collectors.groupingBy(
                    x -> String.join(".",
                            x.getPraefix(),
                            x.getMiddleFix(),
                            x.getPostfix()),
                    Collectors.mapping(Employee::getName, Collectors.toList())

1
Stream.of(x.getPraefix(), x.getMiddleFix(), x.getPostfix()) .collect(Collectors.joining(".") could be replaced with simple concatenation using + - Ivan
@Ivan 哦,谢谢,这就是我一边做两件事情时会发生的事情。 - Eugene
那样就排除了“.”分隔符。我认为第一个更好。 - Vasan
@Vasan 不是这样的 :) 那么第三个选项怎么样(实际上我自己会使用)? - Eugene
啊,是的,我忘记了StringJoiner。+1 - Vasan
@Vasan,顺便说一下,使用String.join可以进一步简化这个过程。 - Eugene

1
您也可以使用toMap收集器:
Map<String, List<String>> resultSet = employees.stream()
             .collect(toMap(e ->
               String.join(".", e.getPraefix(), e.getMiddleFix(), e.getPostfix()),
               v -> new ArrayList<>(Collections.singletonList(v.getName())),
               (left, right) -> {left.addAll(right); return left;}));

今天我想在默认的JDK中使用ArrayList.of(...)HashSet.of(...),这会让代码更加优雅。 - Eugene
@Eugene非常同意,目前的方法确实很冗长。 - Ousmane D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接