Java Streams learning path Level 1 This level · 18 of 25
Easy java streams

Sort employees by salary

The 30 second answer

I sort with a comparator on salary, usually descending, then thenComparing on name as a tie-break. For ordered streams that sort is stable. If names or salaries can be null I say so and use nullsLast so the ordering stays well defined.

Could you say this in an interview?
List<Employee> sorted = emps.stream()
    .sorted(Comparator.comparingDouble(Employee::salary).reversed()
        .thenComparing(Employee::name))
    .toList();

Ordered-source sort is stable. For nulls: Comparator.nullsLast(...).

Sources (2)
  1. Comparator.comparingDouble / reversed / thenComparingdocs.oracle.com
  2. Stream.sorteddocs.oracle.com
Previous
Next