Java Streams learning path Level 2 This level · 8 of 13
Medium java streams

Top 3 highest salaries

The 30 second answer

I take distinct salaries, sort descending, and limit to three. I clarify whether they want the top three salary values or the top three employees. For huge lists a size-three min-heap is better than a full sort, but the stream version is what most interviewers expect first.

Could you say this in an interview?
List<Double> top3 = emps.stream()
    .map(Employee::salary)
    .distinct()
    .sorted(Comparator.reverseOrder())
    .limit(3)
    .toList();

Clarify "top 3 salaries" (distinct values) versus "top 3 employees" (drop distinct).

[Opinion] Optimal for large n: a size-k min-heap, O(n log k).

Sources (2)
  1. Stream (distinct, sorted, limit)docs.oracle.com
  2. Comparatordocs.oracle.com
Previous
Next