Java Stream API Program · OT17
Find the Second Highest Number Using Streams in Java
Remove duplicates, sort from high to low, skip the first element and take the next. The stream returns an Optional, which handles lists with no second value.
Problem Statement
Given a list of integers, return the second highest distinct value. Duplicates of the highest value do not count as a second value.
If there is no second distinct value, for example when all elements are equal, return an empty Optional (printed as none).
Input/Output Examples
[12, 45, 45, 9, 30]Output30Explanation: 45 appears twice, but it is still only the highest value.[7, 7, 7]OutputnoneExplanation: there is only one distinct value.[-5, -1]Output-5Explanation: -1 is the highest, -5 is second.Visual Explanation
- distinct()values1245930the second 45 is removed
- sorted(desc)values4530129reverseOrder()
- skip(1)values4530129drop the highest
- findFirst()Optional[30]
[12, 45, 45, 9, 30]: remove duplicates, sort descending, skip the highest value and take the next one (purple).distinct() must come before skip(1); otherwise the duplicate 45 would be returned as the "second highest". findFirst() returns an empty Optional when nothing is left.
Approaches
The stream version is short and declarative. The loop version, shown for comparison, finds the answer in one pass.
Approach 1: distinct(), sorted() and skip() (Recommended)
Idea: chain distinct(), sorted(Comparator.reverseOrder()), skip(1) and findFirst().
- Remove repeated values with
distinct(). - Sort from highest to lowest.
- Skip the highest and return the next as an
Optional.
Time: O(n log n) · Space: O(n).
Approach 2: One-Pass Loop
Idea: track the highest and second highest distinct values while reading the list once.
- If a value is above
first, shiftfirstintosecond. - Otherwise, if it is below
firstand abovesecond, updatesecond. - Wrap the result in an
Optional.
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: distinct(), sorted() and skip() (Recommended)
Readable and safe for empty or single-value lists, which is why it is a popular Java 8 interview answer.
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class SecondHighestStream {
// distinct() removes repeats of the maximum; skip(1) drops the highest value
static Optional<Integer> secondHighest(List<Integer> numbers) {
return numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
}
public static void main(String[] args) {
List<List<Integer>> inputs = List.of(List.of(12, 45, 45, 9, 30), List.of(7, 7, 7), List.of(-5, -1));
for (List<Integer> list : inputs) {
System.out.println(list + " -> " + secondHighest(list).map(String::valueOf).orElse("none"));
}
}
}
[12, 45, 45, 9, 30] -> 30 [7, 7, 7] -> none [-5, -1] -> -5
Time complexity: O(n log n) · Space complexity: O(n).
Approach 2: One-Pass Loop
Faster for large lists, because it avoids sorting.
import java.util.List;
import java.util.Optional;
public class SecondHighestLoop {
// One pass keeping the two largest distinct values, for comparison with the stream version
static Optional<Integer> secondHighest(List<Integer> numbers) {
Integer first = null;
Integer second = null;
for (int n : numbers) {
if (first == null || n > first) {
second = first;
first = n;
} else if (n < first && (second == null || n > second)) {
second = n;
}
}
return Optional.ofNullable(second);
}
public static void main(String[] args) {
List<List<Integer>> inputs = List.of(List.of(12, 45, 45, 9, 30), List.of(7, 7, 7), List.of(-5, -1));
for (List<Integer> list : inputs) {
System.out.println(list + " -> " + secondHighest(list).map(String::valueOf).orElse("none"));
}
}
}
[12, 45, 45, 9, 30] -> 30 [7, 7, 7] -> none [-5, -1] -> -5
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| distinct(), sorted() and skip() | O(n log n) | O(n) |
| One-Pass Loop | O(n) | O(1) |
Here n is the size of the list. The stream sorts the distinct values; the loop reads each value once with two variables.
Interview Tips and Recommended Approach
- Call
distinct()first. Without it,[45, 45, 30]would return 45. - Return an
Optional. It makes the "no answer" case explicit instead of using a magic number. - Mention the complexity trade-off. Sorting is
O(n log n); a single pass isO(n). - Generalise with
skip(k - 1)for the k-th highest value.
Recommended Approach: distinct(), sorted() and skip()
Why: it is the idiomatic Stream API answer: short, safe for every input and easy to adapt to the k-th highest value.