Second Highest Salary with Streams (and the Nth Highest)
javaJavainterview-prepintermediatejava
Distinct, sort descending, skip one: the stream answer to a favourite interview question, generalised to the Nth highest and safe for short lists.
import java.util.*;
import java.util.stream.*;
public class SecondHighest {
public static void main(String[] args) {
List<Integer> salaries = List.of(50000, 90000, 70000, 90000, 65000);
System.out.println(nthHighest(salaries, 1)); // 90000
System.out.println(nthHighest(salaries, 2)); // 70000
System.out.println(nthHighest(salaries, 3)); // 65000
System.out.println(nthHighest(salaries, 9)); // -1
System.out.println(nthHighest(List.of(10), 2)); // -1
System.out.println(secondHighestLoop(salaries)); // 70000
}
// distinct() makes the two 90000 values count once. O(n log n) because of the sort.
static int nthHighest(List<Integer> values, int n) {
return values.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(n - 1)
.findFirst()
.orElse(-1); // -1 when there are fewer than n distinct values
}
// The same answer in one pass with O(1) extra space, without streams.
static int secondHighestLoop(List<Integer> values) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int v : values) {
if (v > first) {
second = first;
first = v;
} else if (v > second && v != first) {
second = v;
}
}
return second == Integer.MIN_VALUE ? -1 : second;
}
}