Stream#limit可以返回比预期更少的元素吗? [英] Can Stream#limit return fewer elements than expected?

查看:116
本文介绍了Stream#limit可以返回比预期更少的元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果下面的流 s 至少有 n 元素,那么流<$ c的情况是什么$ c> sLimit 可能少于 n 元素(如果有)?

If the Stream s below has at least n elements, what are the situations where the stream sLimit may have less than n elements, if any?

Stream sLimit = s.limit(n);






问题原因:这个答案,我读到:


尽管外观,使用 limit(10)并不一定会产生一个只有10个元素的 SIZED 流 - 它可能会少一些。

Despite the appearances, using limit(10) doesn't necessarily result in a SIZED stream with exactly 10 elements -- it might have fewer.


推荐答案

我认为Holger和Sotirios的答案是准确的,但是因为我是那个发表声明的人,我想我应该解释一下。

I think Holger's and Sotirios' answers are accurate, but inasmuch as I'm the guy who made the statement, I guess I should explain myself.

我主要谈论的是 spliterator特征,特别是 SIZED 特色。这基本上是关于流阶段的静态信息,这些信息在流水线设置时已知,但在流实际执行之前。实际上,它用于确定流的执行策略,因此必须在流执行之前知道它。

I'm mainly talking about spliterator characteristics, in particular the SIZED characteristic. This is basically "static" information about the stream stages that is known at pipeline setup time, but before the stream actually executes. Indeed, it's used for determining the execution strategy for the stream, so it has to be known before the stream executes.

limit() operation创建一个包装其上游spliterator的spliterator,因此 limit spliterator需要确定要返回的特征。即使它的上游分裂器是 SIZED ,它也不知道确切的大小,所以它必须关闭 SIZED 特征。

The limit() operation creates a spliterator that wraps its upstream spliterator, so the limit spliterator needs to determine what characteristics to return. Even if its upstream spliterator is SIZED, it doesn't know the exact size, so it has to turn off the SIZED characteristic.

所以如果你是程序员,那就写:

So if you, the programmer, were to write:

IntStream.range(0, 100).limit(10)

你要说当然该流恰好有10个元素。 (它会。)但是得到的分裂器仍然不是 SIZED 。毕竟, limit 运算符不知道上述与此之间的区别:

you'd say of course that stream has exactly 10 elements. (And it will.) But the resulting spliterator is still not SIZED. After all, the limit operator doesn't know the difference between the above and this:

IntStream.range(0, 1).limit(10)

至少在分裂器特征的条款。

at least in terms of spliterator characteristics.

这就是为什么,即使有时它似乎应该,限制运算符不返回已知大小的流。这又会影响分裂策略,从而影响并行效率。

So that's why, even though there are times when it seems like it ought to, the limit operator doesn't return a stream of known size. This in turn affects the splitting strategy, which impacts parallel efficiency.

这篇关于Stream#limit可以返回比预期更少的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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