What are the differences between findFirst and findAny in Java 8?
I don't really understand the difference between findFirst()
and findAny()
in the Java Stream API.
I thought that findFirst()
returns the first element of the stream, and findAny()
returns the random element of the stream.
But when I run 2 code examples:
Stream.of(...).findFirst()
and Stream.of(...).findAny()
Then they both return the first element of the stream. Why? Are they both doing the same task?
2 answers
Are they both doing the same task?
No. According to JavaDoc Stream#findAny()
:
Returns
Optional<T>
, which stores some stream element, or emptyOptional<T>
if the stream is empty. The behavior of this operation is undefined - it can select any element in the stream. This allows you to ensure maximum performance in parallel operations;
That is, for a non-parallel stream, it will return the first element. And with a parallel stream, it can return any element.
Then how Stream#findFirst()
returns Optional<T>
, which stores strictly the first element of the stream.
Apparently, there is also a misunderstanding of the goals of the existence of Stream.of(...).findAny()
.
You probably shouldn't use this method to generate a random value. Still, it is assumed that this method will be preceded by a filter() with a predicate that will somehow reduce the selection and any (first, fifth, whatever, any means any) element will be taken from this filtered stream.