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

  1. Start with 2 and 1
  2. Do this Take their maximum
  3. Result 2
The stream has elements, so the optional contains the largest value.

Apply it to a real problem

  1. Start with Samples −3, 0, −7 or an empty batch
  2. Do this Read the maximum if present
  3. Result 0 or no samples
Zero is a genuine reading. A batch with no readings has no maximum.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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");
        }
    }
}
Output
0
no samples

Official Java documentation