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

时间:2018-05-15 19:38:03

标签: java arraylist hashmap java-stream

假设我说我有一个名为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将其转换为以下Map?

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

2 个答案:

答案 0 :(得分: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 :(得分: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;}));