Difference between findAny() and findFirst() in Java 8

Mandeep Rajpal picture Mandeep Rajpal · Feb 12, 2016 · Viewed 38k times · Source

I am little confused between Stream#findAny() and Stream#findFirst() of the Stream API in Java 8.

What I understood is that both will return the first matched element from the stream, for example, when used in conjunction with filter?

So, why two methods for the same task? Am I missing something?

Answer

Konstantin Yovkov picture Konstantin Yovkov · Feb 12, 2016

What I understood is that both will return the first matched element from the stream, for example, when used in conjunction with filter?

That's not true. According to the javadoc, Stream#findAny():

Returns an Optional<T> describing some element of the stream, or an empty Optional<T> if the stream is empty. 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;

while Stream.findFirst() will return an Optional<T> describing strictly the first element of the stream. The Stream class doesn't have a .findOne() method, so I suppose you meant .findFirst().