Stream - findFirst vs findAny

4

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 of findFirst that allows better performance for parallel streams (relaxing the requirement to return the first item)?
  • When should I use each of the methods?
asked by anonymous 13.05.2015 / 16:43

1 answer

3
  

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 findAny method offers better performance for parrallelism.

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 java.util.stream package documentation:

  

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

In terms of your other question,

  

When should I use each of the methods?

The main reason is also specified in the documentation findAny :

  

[...]

    
05.06.2015 / 17:16