I have noticed an inconsistency, or difference of opinion regarding findAny() from the Enthuware exams and The Boyarsky/Selikoff OCP 8 book.
So in the book, Chap 7, p372
Since order is not guaranteed with parallel streams, methods such as findAny() on parallel streams may result in unexpected behavior. Let’s take a look at the results of findAny() applied to a serial stream:
This code consistently outputs the first value in the serial stream, 1.
With a parallel stream, the JVM can create any number of threads to process the stream. When you call findAny() on a parallel stream, the JVM selects the first thread to finish the task and retrieves its data:
(Note: < and > in the options below denote the possible output and not the sign themselves.)
With the Answer being:
<An Optional containing 13, 14, or 15>:<An Optional containing 13, 14, or 15>
With the explaination:
The second stream is sequential and therefore, ideally, findAny should return the first element. However, findAny is deliberately designed to be non-deterministic. Its API specifically says that it may return any element from the stream. If you want to select the first element, you should use findFirst.
"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.)
So we clearly have a difference of opinion. I've ran this on my machine and I always get the first element. But the API clearly states that I should not rely on that, and it does not explicitly state that it is nondeterministic for parallel streams exlusively.
Great, and in practice, I would use findFirst() if I wanted the first element regardless of stream. Problem solved... (unless you want to pass the exam)....
So, in an exam, if I were to get a similar question relating to findAny() on a sequential stream, do I:
Select the first element in the stream, as per the book and as per the current implementation of the JDK I am running.
Select the option that could indicate that it could select any element of the stream, because the API says it is non-deterministic.
Really, I understand both sides. I just want to be able to select the option that will give me the mark.