java - 如何使用 Java 流在 groupby 之后应用排序和限制
问题描述
我有以下员工数据列表,我需要根据员工部门对其进行分组,然后我想找到每个部门中薪酬最高的 2 名员工。
public class Employee {
private int id;
private String name;
private String dept;
private int salary;
//setters and getters
}
List<Employee> listOfEmp = new ArrayList<>();
listOfEmp.add(new Employee (1, "A", "IT",100));
listOfEmp.add(new Employee (2, "B", "IT",200));
listOfEmp.add(new Employee (3, "C", "SUPPORT",100));
listOfEmp.add(new Employee (4, "D", "SUPPORT",200));
listOfEmp.add(new Employee (5, "E", "SUPPORT",300));
listOfEmp.add(new Employee (6, "F", "SUPPORT",400));
listOfEmp.add(new Employee (7, "G", "IT",500));
listOfEmp.add(new Employee (8, "H", "IT",600));
listOfEmp.add(new Employee (9, "I", "IT",700));
以下是我写给按部门分组员工的查询
Map<String, List<String>> departmentWiseEmployees = listOfEmp.stream().
collect(Collectors.groupingBy(Employee::getDept, Collectors.mapping(Employee::getName, toList())));
我正在尝试使用以下方法使用以下方法查找每个部门中薪酬最高的 2 名员工。但它是
int limit = 2;
Map<String, List<String>> groupByTeachers =
listOfEmp.stream()
.collect(
Collectors.groupingBy(
Employee::getDept,
Collectors.collectingAndThen(
Collectors.toList(),
e -> e.stream().sorted().limit(limit).collect(toList() ) ) ) );
这里编译器抱怨提供的 lambda 参数出现以下错误collectingAndThen
,它说 e 是类型List<Employee>
,但它必须是List<Object>
有人可以帮助我了解这里出了什么问题吗?
解决方案
这部分代码:
e -> e.stream().sorted().limit(limit).collect(Collectors.toList())
返回 List of List<Employee>
and not List<String>
,因此您可以将结果的类型更改为:
Map<String, List<Employee>> groupByTeachers =
// ...The rest of your code
或者,如果您期望Map<String, List<String>>
,更改collectingAndThen
以获取期望的字段,例如getName
或getDep
:
e -> e.stream().sorted().limit(limit)
.map(Employee::getDep) // for example getDep
.collect(Collectors.toList())
推荐阅读
- python - SSH 上的 Selenium Chrome 浏览器
- sql - 当产品出现在临时表中时,根据临时所有类型的订单的记录更新语句主表
- python - kivy-按下 MDFloatingActionButtonSpeedDial 后如何添加功能
- python - Cloud Pub/Sub 订阅者 max_messages 不适用于消息排序
- r - R中的绘图点在错误的位置?
- python - 如何使用 python 请求和 BeautifulSoup 在网站上的 html 中查找隐藏值
- hl7-v2 - HL7 附加段
- amazon-web-services - 有没有办法导出 AWS RDS MySQL 数据库而不必将其导出到 S3?
- python - 使用 django-haystack 的 whoosh 索引:在 python 2.7 下很快,但在 python 3.7 下真的很慢
- javascript - Electron:使浏览器窗口粘在屏幕的一侧