Stream.count()是否保证访问每个元素? [英] Is Stream.count() guranteed to visit each element?

查看:718
本文介绍了Stream.count()是否保证访问每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换句话说,以下行是否保证打印 num 行?

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

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

此问题是由 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.

StreamDount的JavaDocs 包含以下声明:


这是减少的特例,相当于:

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.

推荐答案

不,不是。由于优化的 count()实现,它不会在Java 9中执行(如果预先知道流大小,它将跳过迭代)。

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).

有关详细信息,请参阅 JDK-8067969 JDK-9中的文档已相应更新:

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.

这篇关于Stream.count()是否保证访问每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆