I have a list of Employee
objects as follows.
public class Employee {
int eno;
String name;
String dept;
int salary;
......
}
The requirement is to get the list of employee names getting the maximum salary in each department. There can be more than one employee having the same highest salary in the department. For example, the Sales team may have 2 employees, say Alex & John, earning the highest salary.
List<Employee> eList = new ArrayList<>();
eList .add(new Employee(101, "ALEX","SALES",7000));
eList.add(new Employee(102, "KATHY","ADMIN",3000));
eList.add(new Employee(103, "JOHN","SALES",7000));
eList.add(new Employee(104, "KONG","IT",5000));
eList.add(new Employee(105, "MIKE","SALES",4000));
The expected output is -> Map(DEPT, List Of Names with max salary)
With the below code, I can get only one Employee object as an output, even though there is more than one employee satisfying the condition.
Map<String, Employee> maxSalEmpNameByDept = eList.stream().collect(groupingBy(Employee::getDept,
collectingAndThen(maxBy(Comparator.comparing(Employee::getSalary)), Optional::get)));
This is because the MaxBy method stops when it finds the fist item that satisfies the given condition.
My questions are:
- How can we get the list of highest-paid Employee's (
Map <String, List<Employee>>
)in each department? - How to retrieve the list of highest-paid employee names alone (
Map <String, List<String>>
) in each department?