gpt4 book ai didi

Java stream groupingBy key作为最高薪水员工和值作为部门的所有员工

转载 作者:行者123 更新时间:2023-12-01 11:51:36 25 4
gpt4 key购买 nike

我有一个 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>>其中映射键是每个部门的最高薪水员工,值是该部门的所有员工。我正在尝试 groupingBy 但它为所有员工提供部门 map 。如何获取所有 max salary employee 作为 map key?

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()));

可能有更好、更有效的解决方案,如果我不在手机上,我可能已经用尽了所有这些想法。

关于Java stream groupingBy key作为最高薪水员工和值作为部门的所有员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62030049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com