How findAny() selects an element in Java stream?

I read in OCP 17 book that findAny on serial stream is not guaranteed to return first element and for parallelStream results are likely to be more random.

  1. Can I somehow achieve such state in which findAny() on serial stream will return element that is not first? Is it possible to achieve this while using standard JDK implementation of the Stream classes?
  2. Is it something like Random class used to pick an element in case of findAny() for parallel stream?

>Solution :

I think the findAny() javadoc answers both questions:

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.
This is a short-circuiting terminal operation.
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. (If a stable result is desired, use findFirst() instead.)

1- no, it is intentionally and explicitly nondeterministic, apparently for performance reasons and better parallel implementation.

2- also no, if you’re talking about .parallelStream() specifically, it’s not that it finds all matches and picks one randomly. Realistically it stops after finding a match but must complete the processing of any part of the stream in other threads before exiting safely. This answer explains the parallel behavior more thoroughly.

Leave a Reply