CKTIS / Java
Stream.max: practical reference
Stream.max: practical reference: max is a terminal reduction that returns the greatest stream element under the supplied Comparator, or Optional.empty for an empty stream.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.max(...)max is a terminal reduction that returns the greatest stream element under the supplied Comparator, or Optional.empty for an empty stream.
Use it when “greatest” comes from an explicit domain ordering; Comparator.comparing can select a key without sorting the whole stream first.
The Comparator must be stateless and non-interfering and define a valid ordering; do not depend on which object is selected among comparator-equal maxima.
If the selected maximum is null, the method throws NullPointerException; a null comparator is also invalid, and the terminal operation consumes the stream.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var result = java.util.stream.Stream.of(3, 1, 2).max(Integer::compareTo);
System.out.println(result.orElse(-1));
}
}
Result
3
The example exercises the documented element in a small deterministic program and compares exact standard output.