我有一个Employee列表

public class Employee {
  private String name;
  private Integer age;
  private Double salary;
  private Department department;
}

List<Employee> employeeList = Arrays.asList(
      new Employee("Tom Jones", 45, 12000.00,Department.MARKETING),
      new Employee("Harry Major", 26, 20000.00, Department.LEGAL),
      new Employee("Ethan Hardy", 65, 30000.00, Department.LEGAL),
      new Employee("Nancy Smith", 22, 15000.00, Department.MARKETING),
      new Employee("Catherine Jones", 21, 18000.00, Department.HR),
      new Employee("James Elliot", 58, 24000.00, Department.OPERATIONS),
      new Employee("Frank Anthony", 55, 32000.00, Department.MARKETING),
      new Employee("Michael Reeves", 40, 45000.00, Department.OPERATIONS));

我想获取Map<Employee, List<Employee>>,其中映射键是每个部门的最高薪水雇员,而值是该部门的所有雇员。
我正在尝试分组,但它为所有员工提供了部门地图。如何获得所有最高薪水雇员作为地图关键字?
Map<Department,List<Employee>> employeeMap
        = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment));

最佳答案

您可以获得以下结果:

Map<Employee, List<Employee>> result = employees.stream()
         .sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
         .collect(groupingBy(Employee::getDepartment, LinkedHashMap::new, toList())).values().stream()
         .collect(toMap(l -> l.get(0), Function.identity()));

那里可能有更好,更有效的解决方案,如果我不接电话,我会精疲力尽。

07-26 04:05