class Employee {
public string department;
public int salary;
}
List<Employee> allEmployees = ...
I need to have a list that will have only 1 top salary employee for each department. allEmployees is the source list.
class Employee {
public string department;
public int salary;
}
List<Employee> allEmployees = ...
I need to have a list that will have only 1 top salary employee for each department. allEmployees is the source list.
You can do that with a grouping collector:
with the static imports
This code creates a
Stream
of all the employees and groups them with their department with the help ofCollectors.groupingBy
. For all the values classified to the same key, we need to keep only the employee with the maximum salary, so we collect them withCollectors.maxBy
and the comparator compares the salary withComparator.comparingInt
. SincemaxBy
returns anOptional<Employee>
(to handle the case where there the list is empty), we wrap it with a call toCollectors.collectingAndThen
with a finisher that just returns the employee: we know in this case that the optional won't be empty.Alternative solution:
When we encounter the first employee from the department, we add a new entry to the
Map
. When another employee is found, one with higher salary is kept. This way you don't need to meddle with optionals.