Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Java Stream findFirst() and findAny()

Reference for Java Stream findFirst() and findAny(): get one element of a stream as an Optional, how they differ in parallel streams, and null handling.

findFirst() and findAny() return one element of a stream wrapped in an Optional. They are terminal, short-circuiting operations, which makes them the usual last step after filter() to answer "give me the first element that matches".

findFirst() honors the stream's encounter order: if the stream is ordered, you get the first element. findAny() may return any element, which allows parallel streams to answer faster. On a sequential stream both almost always return the same thing.

Java
Optional<String> first = names.stream().filter(n -> n.startsWith("B")).findFirst();

Try it

Java Find the first match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Short-circuiting and nulls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
Optional<T> findFirst()
Optional<T> findAny()

Neither method takes parameters.

Returns: an Optional<T> holding an element, or an empty Optional if the stream is empty.

Throws: NullPointerException if the chosen element is null.

Usage notes

  • Order: findFirst() respects encounter order, even in parallel streams, which can limit parallel speed-up. Prefer findAny() when you do not care which element you get.
  • Short-circuit: a pipeline ending in either method stops pulling elements once one is found, so it can finish on an infinite stream.
  • No match is not an error: you get Optional.empty(). Unwrap with orElse(), orElseGet(), orElseThrow() or ifPresent() (see Optional).
  • Null elements: a null selected element throws NullPointerException. Filter nulls with filter(Objects::nonNull) first.
  • Existence only: if you only need to know whether a match exists, use anyMatch().
  • Collections: list.get(0) fails on an empty list, while list.stream().findFirst() does not. Since Java 21 getFirst() on a SequencedCollection also throws on empty.
  • Sorted first: to get the smallest element use min(), not sorted().findFirst(), which sorts everything.