Medium java streams

Find the highest salary in each department

The 30 second answer

I group by department and take the max-salary employee per group with groupingBy and maxBy, which wraps each result in Optional. For a plain map I use toMap with a merge that keeps the higher salary. On ties only one employee is kept unless they ask for every tied person.

Map<String, Optional<Employee>> top = emps.stream()
    .collect(Collectors.groupingBy(
        Employee::dept,
        Collectors.maxBy(Comparator.comparingDouble(Employee::salary))));

// Without Optional wrapping:
Map<String, Employee> top2 = emps.stream()
    .collect(Collectors.toMap(
        Employee::dept,
        e -> e,
        BinaryOperator.maxBy(Comparator.comparingDouble(Employee::salary))));

maxBy yields Optional per group. The toMap merge-function version avoids it. Alternative: collectingAndThen(maxBy(...), Optional::get) — safe because groups from groupingBy are never empty.

Ties: only one employee is kept; say so if the interviewer wants every tied employee.

Sources:

Sources (0)
See inline citations in the answer above.