Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream groupingBy key as max salary employee and value as all employee of department

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));
like image 929
Kmarlon Pereira Avatar asked May 26 '20 19:05

Kmarlon Pereira


People also ask

What is the use of groupingBy in Java 8?

The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance.

How can we fetch the maximum salary of employee using inbuilt method present in java8?

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.

How can I print the nth highest salary in SQL?

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).


1 Answers

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.

like image 77
Ousmane D. Avatar answered Nov 15 '22 05:11

Ousmane D.