Reading up a bit on Java 8, I got to this blog post explaining a bit about streams and reduction of them, and when it would be possible to short-circuit the reduction. At the bottom it states:
Note in the case of
findFirst
orfindAny
we only need the first value which matches the predicate (althoughfindAny
is not guaranteed to return the first). However if the stream has no ordering then we’d expectfindFirst
to behave likefindAny
. The operationsallMatch
,noneMatch
andanyMatch
may not short-circuit the stream at all since it may take evaluating all the values to determine whether the operator istrue
orfalse
. Thus an infinite stream using these may not terminate.
I get that findFirst
or findAny
may short-circuit the reduction, because as soon as you find an element, you do not need to process any further.
But why would this not be possible for allMatch
, noneMatch
and anyMatch
? For allMatch
, if you find one which doesn't match the predicate, you can stop processing. Same for none. And anyMatch
especially doesn't make sense to me, as it it pretty much equal to findAny
(except for what is returned)?
Saying that these three may not short-circuit, because it may take evaluating all the values, could also be said for findFirst/Any
.
Is there some fundamental difference I'm missing? Am I not really understanding what is going on?