Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream.findAny: practical reference

Stream.findAny: practical reference: findAny is a short-circuiting terminal operation that returns an Optional containing some stream element, or an empty Optional for an empty stream.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Stream.findAny(...)

findAny is a short-circuiting terminal operation that returns an Optional containing some stream element, or an empty Optional for an empty stream.

Use it when any matching element is sufficient and its position is irrelevant, especially to avoid imposing encounter order on a parallel pipeline.

The result is explicitly nondeterministic, so repeated executions over equivalent sources may select different elements; do not use it as a stable choice.

Selecting a null element throws NullPointerException, and the stream is consumed after the terminal operation; an empty stream yields Optional.empty.

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").findAny();
        System.out.println(result.isPresent());
    }
}

Result

true

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources