I have the following list of Employee data which I need to group based on the employee department and then I want to find the 2 highest-paid employees in each department.
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));
following is the query I have written to group employees by department
Map<String, List<String>> departmentWiseEmployees = listOfEmp.stream().
collect(Collectors.groupingBy(Employee::getDept, Collectors.mapping(Employee::getName, toList())));
I am trying to use the following method to find the highest 2 paid employees in each department using the following method. but it is
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() ) ) ) );
here compiler complains about following error on the lambda parameter provided for collectingAndThen, it says e is of type List<Employee> but it has to be List<Object>
Could somebody help me to understand what is going wrong here?
