4
The class Stream has two very similar methods, findFirstand findAny. Both return a Optional<T> with an item (or emptycase 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:
findAnyis only a "flexible" implementation offindFirstwhich 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
findAnymay return different results.– mgibsonbr