Core Java

Java 8 Streams findFirst() vs findAny()

Introduction:

Java 8 Stream API has two methods – findFirst() and findAny() which often seem confusing at first. In this article, we’ll learn the differences between the two so that we can choose wisely the next time.

Stream.findAny():

findAny() method is a short-circuiting terminal operation. It returns an Optional<E> describing some element of the stream or an empty Optional for an empty stream.

Optional<Integer> anyElement = Stream.of(1, 2, 3, 4).findAny();

In a non-parallel pipeline, it usually returns the first element in the stream as an outcome.

However, based on the JavaDocs definition, the behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations.

Optional<Integer> anyElement = Stream.of(1, 2, 3, 4).parallel().findAny();

Stream.findFirst():

As the name suggests, the findFirst() method strictly returns the first element in a given Stream.

Optional<Integer> firstElement = Stream.of(1, 2, 3, 4).findFirst();

The only exception to it is a missing encounter order(very unlikely), for which it would return any random element from the stream.

JavaDoc on Streams API clearly states that:

Streams may or may not have a defined encounter order. It depends on the source and the intermediate operations.

Just like findAny(), our findFirst() method also returns an empty Optional, in case of an empty stream. It is advised to use the findFirst() method when we specifically need to find the very first element, be it in a parallel or a non-parallel stream.

 

Differences In A NutShell:

findAny()findFirst()
Has a non-deterministic outcome; returns any element in the streamHas a deterministic outcome; strictly returns the first element
Usually returns a first element in a non-parallel streamAlways returns the first element in any stream(parallel/non-parallel)
Use it when you just need to check if atleast one element exists in the streamUse if to find the very first element in the stream

Conclusion:

In this quick guide, we looked at the difference between findFirst() and findAny() methods exposed in Java Stream API. We now know that findAny() has a non-deterministic outcome and helps gain performance improvements when working with parallel streams in a few scenarios.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *