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.
Optional<String> first = names.stream().filter(n -> n.startsWith("B")).findFirst();
Try it
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.
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
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. PreferfindAny()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 withorElse(),orElseGet(),orElseThrow()orifPresent()(seeOptional). - Null elements: a
nullselected element throwsNullPointerException. Filter nulls withfilter(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, whilelist.stream().findFirst()does not. Since Java 21getFirst()on aSequencedCollectionalso throws on empty. - Sorted first: to get the smallest element use
min(), notsorted().findFirst(), which sorts everything.
Related
stream-match,stream-filter,class-optional- Lessons: Streams, Optional