Java and Spring Level 2 This level · 16 of 84
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.

Could you say this in an interview?
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 (2)
  1. Collectors (groupingBy, maxBy, toMap)docs.oracle.com
  2. Comparatordocs.oracle.com
Previous
Next