从包含部门列表的员工对象中制作部门到员工列表的映射

Var*_*dav 6 java java-stream

问题: Employee 包含部门列表,我们有一个员工列表,现在如何从员工列表中获取像 Map<Department,List of Members> 这样的地图。

下面的代码可以解决这个问题,但我想知道如何有效地使用流 api 而不是 for 循环。

    Department a = new Department("a");
    Department b = new Department("b");
    Department c = new Department("c");

    Employee e1 = new Employee("e1", List.of(a, b));
    Employee e2 = new Employee("e2", List.of(c, b));
    Employee e3 = new Employee("e3", List.of(c, a));
    Employee e4 = new Employee("e4", List.of(a, b, c));

    List<Employee> employees = List.of(e1, e2, e3, e4);
    Set<Department> departments = employees.stream().flatMap(employee ->
            employee.getDepartments().stream()).collect(Collectors.toSet());

    for (Department d : departments) {
        for (Employee employee : employees) {
            if (employee.getDepartments().contains(d)) {
                if (!result.containsKey(d)) {
                    result.put(d, new ArrayList<Employee>());
                }
                result.get(d).add(employee);
            }
        }
    }
    return result;
Run Code Online (Sandbox Code Playgroud)

tev*_*dar 5

即使没有任何流魔法,也可能值得一提的是,您只需要一个循环对,而不是您已有的循环对(员工及其部门):

[...]
List<Employee> employees = List.of(e1, e2, e3, e4);
for (Employee employee : employees) {
    for (Department d : employee.getDepartments()) {
        if (!result.containsKey(d)) {
            result.put(d, new ArrayList<Employee>());
        }
        result.get(d).add(employee);
    }
}
return result;
Run Code Online (Sandbox Code Playgroud)

然后你可以尝试一些神奇的流平面地图分组:

[...]
List<Employee> employees = List.of(e1, e2, e3, e4);
var result = employees.stream().flatMap(employee->employee.getDepartments().stream()
        .map(department->AbstractMap.SimpleImmutableEntry<>(department,employee))
    .collect(Collectors.groupingBy(pair->pair.getKey()));
Run Code Online (Sandbox Code Playgroud)

这里的缺点是这result将是一个Map<Department,AbstractMap.SimpleImmutableEntry<Department,Employee>. (AbstractMap.SimpleImmutableEntry是一个 2 元素元组,只是它有一个很好听的长名称)。

上面的代码片段里面可能有拼写错误,实际上我只使用 aMap<String,List<String>>作为员工部门来运行你的任务,因为我不想编写补充类:

public static void main(String[] args) {
    var a="a";
    var b="b";
    var c="c";
    var empdep=new HashMap<String, List<String>>();
    empdep.put("e1", List.of(a, b));
    empdep.put("e2", List.of(c, b));
    empdep.put("e3", List.of(c, a));
    empdep.put("e4", List.of(a, b, c));
    System.out.println(empdep);
    
    var depemp=new HashMap<String, List<String>>();
    for(var employee:empdep.entrySet())
        for(var department:employee.getValue()) {
            if(!depemp.containsKey(department))
                depemp.put(department, new ArrayList<String>());
            depemp.get(department).add(employee.getKey());
        }
    System.out.println(depemp);
        
    System.out.println(
            empdep.entrySet().stream().flatMap(employee->employee.getValue().stream()
                    .map(department->new AbstractMap.SimpleImmutableEntry<>(department, employee.getKey())))
                    .collect(Collectors.groupingBy(pair->pair.getKey()))
            );
}
Run Code Online (Sandbox Code Playgroud)

这段代码输出

{e1=[a, b], e2=[c, b], e3=[c, a], e4=[a, b, c]}
{a=[e1, e3, e4], b=[e1, e2, e4], c=[e2, e3, e4]}
{a=[a=e1, a=e3, a=e4], b=[b=e1, b=e2, b=e4], c=[c=e2, c=e3, c=e4]}
Run Code Online (Sandbox Code Playgroud)

其中第一行是输入“列表”(这里只是一个映射,但对其进行循环entrySet()与列表完全相同),第二行是 for 循环对的结果,生成所需的映射,并且第三行是流魔法的结果,但在部门“内部”有一个部门-员工对的列表。


那是昨天,今天也是今天。groupingBy()我对和有了更多的了解mapping()。这条“线”

System.out.println(
    empdep.entrySet().stream().flatMap(employee->employee.getValue().stream()
        .map(department->new AbstractMap.SimpleImmutableEntry<>(department, employee.getKey())))
        .collect(Collectors.groupingBy(pair->pair.getKey(),Collectors.mapping(pair->pair.getValue(), Collectors.toList()))));
Run Code Online (Sandbox Code Playgroud)

使用前面的 String-String 示例生成所需的输出,

{a=[e1, e3, e4], b=[e1, e2, e4], c=[e2, e3, e4]}
Run Code Online (Sandbox Code Playgroud)

然后是完整的代码,以及EmployeeDepartment

public class Test {
    public static void main(String[] args) {
        Department a = new Department("a");
        Department b = new Department("b");
        Department c = new Department("c");

        Employee e1 = new Employee("e1", List.of(a, b));
        Employee e2 = new Employee("e2", List.of(c, b));
        Employee e3 = new Employee("e3", List.of(c, a));
        Employee e4 = new Employee("e4", List.of(a, b, c));

        List<Employee> employees = List.of(e1, e2, e3, e4);
        Map<Department,List<Employee>> result=employees.stream()
            .flatMap(employee->employee.getDepartments().stream()
                .map(department->new Pair(department,employee)))
            .collect(Collectors.groupingBy(pair->pair.d,
                                           Collectors.mapping(pair->pair.e,
                                                              Collectors.toList())));
        System.out.println(result);
    }
    
    static class Department{final String name;Department(String name){this.name=name;}public String toString(){return name;}}
    static class Employee{final String name;final List<Department> departments;Employee(String name,List<Department> departments){this.name=name;this.departments=departments;}List<Department> getDepartments(){return departments;}public String toString() {return name;}}
    // this is just a helper class instead of AbstractMap.whatever
    static class Pair{final Department d;final Employee e;Pair(Department d,Employee e){this.d=d;this.e=e;}}
}
Run Code Online (Sandbox Code Playgroud)

此代码产生所需的Map<Department,List<Employee>> result,并打印

{b=[e1, e2, e4], a=[e1, e3, e4], c=[e2, e3, e4]}
Run Code Online (Sandbox Code Playgroud)

也在IdeOne上