目标是找到部门中最新员工的工资,考虑到员工ID将增加。我已经编写了一个两步代码,我正试图找到一个可以使用java8在一步中完成这项工作的解决方案。
我的流程是:
- 获取";部门":"最新员工";基于该部门最大的雇员ID
- 使用上一个映射创建";部门":"最新雇员的工资";(这是输出(
是否可以在一个步骤中完成?
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
Employee e1 = new Employee(1, 1000, "a1", "A");
Employee e2 = new Employee(2, 1010, "b1", "A");
Employee e3 = new Employee(3, 1000, "a1", "B");
Employee e4 = new Employee(4, 500, "b2", "B");
Employee e5 = new Employee(5, 2000, "a1", "C");
Employee e6 = new Employee(6, 5000, "b2", "C");
employees.add(e1);
employees.add(e2);
employees.add(e3);
employees.add(e4);
employees.add(e5);
employees.add(e6);
//This Map will contain Department and The newest Employee in that Department.
Map<String, Employee> retVal = employees.stream()
.collect(groupingBy(
e -> e.getDepartment(),
collectingAndThen(maxBy(comparingInt(e -> e.getEmployeeId())), Optional::get)
));
//This Map will use the previous map to construct a combination of "Department" : "Salary of the newest Member"
Map<String, Integer> map = new HashMap<>();
retVal.entrySet().forEach(stringEmployeeEntry -> {
map.put(stringEmployeeEntry.getKey(), stringEmployeeEntry.getValue().getSalary());
});
}
输出
{
"a1" : 2000,
"b1" : 1010,
"b2" : 5000,
}
您可以直接从Employee
对象映射collectingAndThen
中的薪资
Map<String, Integer> retVal = employees.stream()
.collect(Collectors.groupingBy(
e -> e.getDepartment(),
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingInt(e -> e.getEmployeeId())),
e -> e.get().getSalary())
));