Is Java 8 findFirst().isPresent() more efficient than count() > 0?

前端 未结 3 1892
醉酒成梦
醉酒成梦 2021-02-19 10:00

Given I have a stream Stream stream = list.stream().filter(some predicate) where the list is very large, is it more efficient to check whether the stream

3条回答
  •  孤城傲影
    2021-02-19 10:47

    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.

提交回复
热议问题