fork(1) download
  1. import java.util.List;
  2. import java.util.Map;
  3. import java.util.stream.Collectors;
  4.  
  5. class Ideone {
  6. public static void main(String[] args) {
  7. Department a = new Department("a");
  8. Department b = new Department("b");
  9. Department c = new Department("c");
  10.  
  11. Employee e1 = new Employee("e1", List.of(a, b));
  12. Employee e2 = new Employee("e2", List.of(c, b));
  13. Employee e3 = new Employee("e3", List.of(c, a));
  14. Employee e4 = new Employee("e4", List.of(a, b, c));
  15.  
  16. List<Employee> employees = List.of(e1, e2, e3, e4);
  17. Map<Department,List<Employee>> result=employees.stream()
  18. .flatMap(employee->employee.getDepartments().stream()
  19. .map(department->new Pair(department,employee)))
  20. .collect(Collectors.groupingBy(pair->pair.d,
  21. Collectors.mapping(pair->pair.e,
  22. Collectors.toList())));
  23. System.out.println(result);
  24. }
  25.  
  26. static class Department{final String name;Department(String name){this.name=name;}public String toString(){return name;}}
  27. 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;}}
  28. // this is just a helper class instead of AbstractMap.whatever
  29. static class Pair{final Department d;final Employee e;Pair(Department d,Employee e){this.d=d;this.e=e;}}
  30. }
Success #stdin #stdout 0.11s 48512KB
stdin
Standard input is empty
stdout
{a=[e1, e3, e4], c=[e2, e3, e4], b=[e1, e2, e4]}