"unordered" 如何帮助 "distinct()" 和 "groupingBy"

How "unordered" helps "distinct()" and "groupingBy"

我正在学习 Oracle 的 Stream API Java 1.8 课程,我在仔细阅读讲义时偶然发现了这个:

unordered():

– Inherited from BaseStream

– Returns a stream that is unordered (used internally)

– Can improve efficiency of operations like distinct() and groupingBy()

这是我的问题。无序的 属性 如何导致更有效地计算 distinct()groupingBy()

只有在并行流的情况下才有意义。在有序并行流的情况下,distinct() 操作必须做额外的工作以保持其稳定性保证,即

for duplicated elements, the element appearing first in the encounter order is preserved

(参见javadoc for Stream.distinct()中的API注释部分。

在无序并行流的情况下,不需要保留这样的保证,因为流已经是无序的。这样,从有序并行流中去除有序特征可以大大提高 distinct() 操作的性能。

同样,对于groupingBy()操作,取消保留流顺序的要求可以在并行流的情况下大大提高操作效率,因为归约本身可以并发执行。请注意,这只会发生在使用并发收集器从并行流中收集时,收集器或流本身是无序的。实际上,您需要使用 Stream.collect(groupingByConcurrent(..)) 而不是 Stream.collect(groupingBy(..))。有关详细信息,请参阅 Stream.collect() and Collector 的 javadoc。