简体   繁体   中英

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:

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?

{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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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