Stream -> findFirst vs findAny

Asked

Viewed 986 times

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:

  • findAny is only a "flexible" implementation of findFirst which allows better performance for parallel streams (relaxing the requirement to return the first item)?
  • When to use each method?
  • 1

    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.

1 answer

4


findAny is just a "flexible" implementation of findFirst that allows better performance for parallel streams (by relaxing the requirement to return the first item)?

Correct. The method findAny provides better performance for parralelismo.

Documentation of findAny :

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; the cost is that Multiple invocations on the same source may not Return the same result.

It is one of the few methods where the result can change using parallelism as mentioned in the package documentation java.util.stream :

Except for Operations identified as explicitly nondeterministic, such as findAny(), whether a stream executes sequentially or in Parallel should not change the result of the computation.

In terms of your other question,

When to use each method?

The main reason is also specified in the documentation of findAny :

[...] (If a stable result is desired, use findFirst() Instead.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.