The 30 second answer
Same pattern as second-highest: distinct salaries, descending sort, skip n minus one, findFirst. I validate that n is at least one because skip rejects negatives, and I return empty Optional when there are fewer than n distinct values.
Could you say this in an interview?
Optional<Double> nth = emps.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(n - 1)
.findFirst();Validate n >= 1 โ skip throws IllegalArgumentException for a negative argument. Return Optional.empty() when fewer than n distinct salaries exist.
Sources (1)
- Stream.skip / findFirst / distinctdocs.oracle.com