I have a list of Employee
public class Employee {
private String name;
private Integer age;
private Double salary;
private Department department;
}
List<Employee> employeeList = Arrays.asList(
new Employee("Tom Jones", 45, 12000.00,Department.MARKETING),
new Employee("Harry Major", 26, 20000.00, Department.LEGAL),
new Employee("Ethan Hardy", 65, 30000.00, Department.LEGAL),
new Employee("Nancy Smith", 22, 15000.00, Department.MARKETING),
new Employee("Catherine Jones", 21, 18000.00, Department.HR),
new Employee("James Elliot", 58, 24000.00, Department.OPERATIONS),
new Employee("Frank Anthony", 55, 32000.00, Department.MARKETING),
new Employee("Michael Reeves", 40, 45000.00, Department.OPERATIONS));
I want to get Map<Employee, List<Employee>>
where map key is for each Department's max salary employee and value is all employee of that department.
I am trying to groupingBy but it gives all employee with Department map. How to get all max salary employee as map key ?
Map<Department,List<Employee>> employeeMap
= employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment));
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance.
maxBy() method finds the Employee with the maximum salary and prints it as “ Employee Name:Tom Jones Age:45 Salary:15000.0 ”. Employee details are printed as per the formatting defined in the overridden toString() method in the Employee POJO class.
Select Emp_name from table_name where Salary =( Select Salary from table_name order by Salary DESC limit n-1,1); There can be another question like find Nth Lowest Salary . In order to that , just reverse order using ASC ( if you don't specify by default column will be ordered in ascending order).
You can get the required result as follows:
Map<Employee, List<Employee>> result = employees.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
.collect(groupingBy(Employee::getDepartment, LinkedHashMap::new, toList())).values().stream()
.collect(toMap(l -> l.get(0), Function.identity()));
There's probably better and more efficient solutions out there and I would have exhausted those ideas had i not been on my phone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With