使用 Java 流根据工资检索员工部门和 ID

Retrieving employee department and id based on the salary using Java streams

我有一份员工名单

[employeeId=22, employeeName= Rajan Anand, department= Engineering, salary=1600000]

[employeeId=23, employeeName= Swati Patil, department= Testing, salary=800000]

[employeeId=27, employeeName= Vijay Chawda, department= Engineering, salary=800000]

[employeeId=29, employeeName= Basant Mahapatra, department= Engineering, salary=600000]

[employeeId=32, employeeName= Ajay Patel, department= Testing, salary=350000]

[employeeId=34, employeeName= Swaraj Birla, department= Testing, salary=350000]

我想在 Map<String,Integer>.

中收集该部门中工资最高的员工的部门和 ID

示例输出:

Engineering 22

Testing 23

尝试的代码

Map<String, Optional<Employee>> retVal = new HashMap<String, Optional<Employee>>();
retVal = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment,Collectors.maxBy(Comparator.comparing(Employee::getSalary))));

我添加了这个实现,我将部门作为键并将最高薪水员工作为值,但我只希望员工 ID 作为值。

你可以这样做:

Map<String, Optional<Integer>> result =  employeeList.stream()
     .collect(Collectors.groupingBy(Employee::getDepartment,
              Collectors.collectingAndThen(Collectors
                   .maxBy(Comparator.comparing(Employee::getSalary)),
                                            e-> e.map(Employee::getEmployeeId))));

DEMO

#1 - 当前方法

如果您尝试过,您可以扩展相同的管道以再次流式传输条目并将值映射如下:

Map<String, Optional<Integer>> retVal = employeeList.stream()
        .collect(Collectors.groupingBy(Employee::getDepartment,
                Collectors.maxBy(Comparator.comparing(Employee::getSalary))))
        .entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                e -> e.getValue().map(Employee::getId)));

#2 - 单流方法

现在,如果您要寻找对条目流式处理的抽象并使用单个 collect 操作执行操作,那么您可以使用 .

#3 - 查找方法

作为一个建议(虽然有两次迭代),如果我要扩展它并使其灵活以供进一步使用,我会首先准备一个查找映射,从 id 到员工的薪水

Map<Integer, Integer> employeeSalary = employeeList.stream()
        .collect(Collectors.toMap(Employee::getId, Employee::getSalary));

使用这张地图进一步实现你目前想要的映射也很方便,例如:

Map<String, Integer> retVal = employeeList.stream()
        .collect(Collectors.toMap(Employee::getDepartment, Employee::getId,
                BinaryOperator.maxBy(Comparator.comparing(employeeSalary::get))));