流有序/无序问题 [英] Stream ordered/unordered problems

查看:139
本文介绍了流有序/无序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

Set<Integer> l = new TreeSet<>();
l.add(1);
l.add(10);
l.add(3);
l.add(-3);
l.add(-4);

并且我想通过以下方式取消收藏集的顺序:

and I want to unorder the collection with:

l.stream().unordered().forEach(System.out::println);

,但是forEach总是返回已排序的集合!

but the forEach returns always the collection ordered!

然后,我对来自此处:

对于顺序流,是否存在遇到顺序 不影响性能,仅影响确定性.如果订购了流, 在相同的对象上重复执行相同的流管道 源将产生相同的结果;如果没有订购, 重复执行可能会产生不同的结果.

For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.

实际上,如果我在无序流上尝试此代码,则结果始终是相同的,并且永远不会产生不同的结果:

In fact if I try this code on an unordered stream the results is always the same and never produce different results:

Arrays.stream( new int[]{8, -1, 3}).forEach(System.out::println);
Arrays.stream( new int[]{8, -1, 3}).forEach(System.out::println);

我真的不理解这个API部分...

I really don't understand this API part...

推荐答案

unordered()操作不会执行任何操作来显式取消流的顺序.它的作用是消除了必须保持有序的流的约束,从而允许后续操作使用不必考虑有序的优化.

The unordered() operation doesn't do any actions to explicitly unorder the stream. What it does is that it removes the constraint on the stream that it must remain ordered, thereby allowing subsequent operations to use optimizations that don't have to take ordering into consideration.

您可以在 Java 8文档:

对于顺序流,是否存在相遇顺序不会影响性能,只会影响确定性.如果订购了一个流,则在相同的源上重复执行相同的流管道将产生相同的结果;如果未订购,则重复执行可能会产生不同的结果.
对于并行流,放宽排序约束有时可以使执行更有效率.

...

For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.
For parallel streams, relaxing the ordering constraint can sometimes enable more efficient execution.

...

如果流具有遇到顺序,但用户并不特别关心该遇到顺序,则使用unordered()对流进行明确排序可以改善某些有状态或终端操作的并行性能./em>

In cases where the stream has an encounter order, but the user does not particularly care about that encounter order, explicitly de-ordering the stream with unordered() may improve parallel performance for some stateful or terminal operations.

这篇关于流有序/无序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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