CKTIS / Java
Stream.findFirst: practical reference
Stream.findFirst: practical reference: findFirst is a short-circuiting terminal operation that returns the first element in encounter order for an ordered stream, or Optional.empty when empty.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.findFirst(...)findFirst is a short-circuiting terminal operation that returns the first element in encounter order for an ordered stream, or Optional.empty when empty.
Use it when selection must be stable with respect to source order, such as taking the first record that remains after filter.
Preserving encounter order can constrain parallel performance; if the stream has no encounter order, any element may be returned.
A selected null throws NullPointerException, an empty stream merely returns Optional.empty, 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("a", "b").findFirst();
System.out.println(result.orElse("none"));
}
}
Result
a
The example exercises the documented element in a small deterministic program and compares exact standard output.