The Stream class has two very similar methods, findFirst
and findAny
. Both return a Optional<T>
with an item (or empty
if Stream
is empty).
The findFirst
returns the first found item. In practice it seems that findAny
is also returning the first item of Stream
:
IntStream.range(1, 10).filter(n -> n % 2 == 0).findFirst().getAsInt(); // 2
IntStream.range(1, 10).filter(n -> n % 2 == 0).findAny().getAsInt(); // 2
In this sense, I did not really understand what exactly the findAny
method should do:
-
Is
findAny
just a "flexibilized" implementation offindFirst
that allows better performance for parallel streams (relaxing the requirement to return the first item)? - When should I use each of the methods?