Is Stream.count() guranteed to visit each element?

前端 未结 1 1557
闹比i
闹比i 2020-12-16 22:05

In other words, is the following line guranteed to print num lines?

int num = list.stream().peek(System.out::println).count();

相关标签:
1条回答
  • 2020-12-16 22:25

    Nope, it's not. It will not do it in Java 9 due to optimized count() implementation (if stream size is known in advance, it will skip iteration).

    See JDK-8067969 for more details. The documentation in JDK-9 was updated accordingly:

    An implementation may choose to not execute the stream pipeline (either sequentially or in parallel) if it is capable of computing the count directly from the stream source. In such cases no source elements will be traversed and no intermediate operations will be evaluated. Behavioral parameters with side-effects, which are strongly discouraged except for harmless cases such as debugging, may be affected.

    0 讨论(0)
提交回复
热议问题