用于为每个部门选择最高薪员工的 Java 8 lambda [英] Java 8 lambda for selecting top salary employee for each department

查看:20
本文介绍了用于为每个部门选择最高薪员工的 Java 8 lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Employee {
    public string department;
    public int salary;
}

List<Employee> allEmployees = ...

我需要一个列表,其中每个部门只有 1 名最高薪员工.allEmployees 是源列表.

I need to have a list that will have only 1 top salary employee for each department. allEmployees is the source list.

推荐答案

您可以使用分组收集器来做到这一点:

You can do that with a grouping collector:

Map<String, Employee> topEmployees =
    allEmployees.stream()
                .collect(groupingBy(
                    e -> e.department,
                    collectingAndThen(maxBy(comparingInt(e -> e.salary)), Optional::get) 
                ));

使用静态导入

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.maxBy;

此代码创建了所有员工的 Stream,并在 Collectors.groupingBy.对于所有归类到同一个key的值,我们只需要保留工资最高的那个员工,所以我们用Collectors.maxBy 并且比较器将工资与 Comparator.comparingInt.由于 maxBy 返回一个 Optional(以处理列表为空的情况),我们用对 Collectors.collectingAndThen 带有一个只返回员工的完成者:我们知道在这种情况下,可选不会为空.

This code creates a Stream of all the employees and groups them with their department with the help of Collectors.groupingBy. For all the values classified to the same key, we need to keep only the employee with the maximum salary, so we collect them with Collectors.maxBy and the comparator compares the salary with Comparator.comparingInt. Since maxBy returns an Optional<Employee> (to handle the case where there the list is empty), we wrap it with a call to Collectors.collectingAndThen with a finisher that just returns the employee: we know in this case that the optional won't be empty.

这篇关于用于为每个部门选择最高薪员工的 Java 8 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆