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

落花浮王杯 提交于 2020-01-10 19:33:30

问题


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

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

This question was triggered by a discussion in the comments of https://stackoverflow.com/a/41346586/2513200

I vaguely remember a discussion that optimizations that avoid iteration might be legal, but didn't find anything conclusive during a quick search.

The JavaDocs for Stream.count contain this statement:

This is a special case of a reduction and is equivalent to:
return mapToLong(e -> 1L).sum();

but I'm not sure whether this provides any guarantees if the stream can somehow determine the result in a short-circuiting way.


回答1:


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.



来源:https://stackoverflow.com/questions/41347083/is-stream-count-guranteed-to-visit-each-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!