Java8 Streams findFirst and findAny Examples
findFirst()
and findAny()
are methods in the Stream
interface in Java that are used to find the first or any element in a stream that matches a given condition.
Java8 Streams FindFirst
findFirst()
returns an Optional
object, which contains the first element in the stream that matches the given condition. If no elements match the condition, an empty Optional
is returned.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
Optional<Integer> firstEvenNumber = numbers.stream()
.filter(n -> n % 2 == 0)
.findFirst();
Java8 Streams FindAny
findAny()
also returns an Optional
object, which contains any element in the stream that matches the given condition. If no elements match the condition, an empty Optional
is returned.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
Optional<Integer> anyEvenNumber = numbers.stream()
.filter(n -> n % 2 == 0)
.findAny();
It’s important to note that both findFirst()
and findAny()
are short-circuiting operations, meaning that they will stop processing the stream as soon as they find the first or any element that matches the given condition. So, the time complexity of both methods is O(1) on average, and O(n) in the worst case.
Also, using findFirst()
or findAny()
on a parallel stream will return the first or any element encountered in an unspecified order, but using them on a sequential stream will return the first or any element in the encounter order.