4
The class Stream has two very similar methods, findFirst
and findAny
. Both return a Optional<T>
with an item (or empty
case to Stream
be empty).
The findFirst
returns the first item found. In practice it seems that the findAny
is also returning the first item from 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 understand what exactly the method findAny
should do:
findAny
is only a "flexible" implementation offindFirst
which allows better performance for parallel streams (relaxing the requirement to return the first item)?- When to use each method?
I don’t have an answer, but I think that your first statement is correct. If the streams are simple, both return the first element and that’s it. But if they are parallel, not necessarily, including the documentation says that two calls equal to
findAny
may return different results.– mgibsonbr