Find a maximum when a stream may be empty in Java
IntStream.max returns an OptionalInt. Test presence before printing so a genuine maximum of zero remains distinguishable from an empty input.
A simple example
Take their maximum
- Start with 2 and 1
- Do this Take their maximum
- Result 2
Apply it to a real problem
- Start with Samples −3, 0, −7 or an empty batch
- Do this Read the maximum if present
- Result 0 or no samples
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) throws Exception {
for (int[] batch : new int[][]{{-3, 0, -7}, {}}) {
var max = IntStream.of(batch).max();
System.out.println(max.isPresent() ? Integer.toString(max.getAsInt()) : "no samples");
}
}
}
0 no samples