Given I have a stream Stream
where the list is very large, is it more efficient to check whether the stream
findAny
(which is preferable to findFirst
if you do not need ordering) and anyMatch
are short-circuiting operations, which means they can return early without consuming the entire stream if the conditions allow. This is mentioned and linked in their method javadocs. count()
is not.
If the stream's final stage still uses a spliterator with the SIZED characteristic then count()
may be as fast as the other two options. But this is a far weaker property than short-circuiting since intermediate stream operations – such as filter()
– are very likely to discard the SIZED aspect.
All this information can be gleaned from the package documentation, it's highly recommended reading.