fork(1) download
  1. import java.util.List;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import java.util.function.Function;
  5. import java.util.stream.Collectors;
  6.  
  7. class Department {
  8. String deptId;
  9.  
  10. public Department(String deptId) {
  11. this.deptId = deptId;
  12. }
  13.  
  14. public String getDeptId() {
  15. return deptId;
  16. }
  17.  
  18. @Override
  19. public String toString() {
  20. return "Department [deptId=" + deptId + "]";
  21. }
  22. }
  23.  
  24. class Employee {
  25. String empId;
  26. List<Department> departments;
  27.  
  28. public Employee(String empId, List<Department> departments) {
  29. this.empId = empId;
  30. this.departments = departments;
  31. }
  32.  
  33. public String getEmpId() {
  34. return empId;
  35. }
  36.  
  37. public List<Department> getDepartments() {
  38. return departments;
  39. }
  40.  
  41. @Override
  42. public String toString() {
  43. return "Employee [empId=" + empId + ", departments=" + departments + "]";
  44. }
  45. }
  46.  
  47. public class Main {
  48. public static void main(String[] args) {
  49. Department a = new Department("a");
  50. Department b = new Department("b");
  51. Department c = new Department("c");
  52.  
  53. Employee e1 = new Employee("e1", List.of(a, b));
  54. Employee e2 = new Employee("e2", List.of(c, b));
  55. Employee e3 = new Employee("e3", List.of(c, a));
  56. Employee e4 = new Employee("e4", List.of(a, b, c));
  57.  
  58. List<Employee> employees = List.of(e1, e2, e3, e4);
  59. Set<Department> departments = employees.stream().flatMap(employee -> employee.getDepartments().stream())
  60. .collect(Collectors.toSet());
  61.  
  62. Map<Department, List<Employee>> map =
  63. departments.stream()
  64. .collect(Collectors.toMap(
  65. Function.identity(),
  66. d -> employees.stream().filter(e -> e.getDepartments().contains(d)).collect(Collectors.toList())
  67. )
  68. );
  69.  
  70. map.entrySet().forEach(System.out::println);
  71. }
  72. }
Success #stdin #stdout 0.19s 53904KB
stdin
Standard input is empty
stdout
Department [deptId=c]=[Employee [empId=e2, departments=[Department [deptId=c], Department [deptId=b]]], Employee [empId=e3, departments=[Department [deptId=c], Department [deptId=a]]], Employee [empId=e4, departments=[Department [deptId=a], Department [deptId=b], Department [deptId=c]]]]
Department [deptId=a]=[Employee [empId=e1, departments=[Department [deptId=a], Department [deptId=b]]], Employee [empId=e3, departments=[Department [deptId=c], Department [deptId=a]]], Employee [empId=e4, departments=[Department [deptId=a], Department [deptId=b], Department [deptId=c]]]]
Department [deptId=b]=[Employee [empId=e1, departments=[Department [deptId=a], Department [deptId=b]]], Employee [empId=e2, departments=[Department [deptId=c], Department [deptId=b]]], Employee [empId=e4, departments=[Department [deptId=a], Department [deptId=b], Department [deptId=c]]]]