我正在努力寻找每个部门最新员工的工资。一步到位地使用Java8
目标是在考虑到员工ID将增加的情况下,找到部门中最新员工的工资。 我已经编写了一个两步代码,我正试图找到一个解决方案,使用java8一步就可以做到这一点 我的过程是:我正在努力寻找每个部门最新员工的工资。一步到位地使用Java8,java,java-8,java-stream,collectors,maxby,Java,Java 8,Java Stream,Collectors,Maxby,目标是在考虑到员工ID将增加的情况下,找到部门中最新员工的工资。 我已经编写了一个两步代码,我正试图找到一个解决方案,使用java8一步就可以做到这一点 我的过程是: 获取“部门”地图:“最新员工”基于该部门最大的员工ID 使用前面的映射创建“部门”:“最新员工的工资”(这是输出) 有可能一步到位吗 public static void main(String[] args) { List<Employee> employees = new ArrayList<
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());
});
}
您可以直接在
collecting中映射薪资,然后从Employee
对象映射薪资
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())
));
Map retVal=employees.stream()
.collect(收集器.groupingBy(
e->e.getDepartment(),
收藏,收藏,然后(
Collectors.maxBy(Comparator.comparingit(e->e.getEmployeeId()),
e->e.get().getSalary())
));
谢谢,完全错过了这一部分。。现在可以正常工作坦率地说,使用静态导入的收集器
对我来说可读性较差(当然这是一个品味问题)。你能至少提一下吗?共有新用户访问此网站:)
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())
));