简体   繁体   English

Java Stream API:如何转换为集合映射

[英]Java Stream API: how to convert to a Map of Sets

Lets say I have following an class named Employee and a List of these Employee -classes: 假设我有一个名为Employee的类和这些Employee -classes的列表:

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"));

Is it possible to convert it to following Map with Java Stream-API? 是否可以使用Java Stream-API将其转换为以下Map?

{A.B.C=[Cristiano Ronaldo, Michael Phelps], D.E.F=[Aydin Korkmaz, Diego Armando Maradona, Usain Bolton]} 
  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())

You could also use the toMap collector: 您也可以使用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;}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM