搜索不一致行为 java-8 流的示例? [英] search for example of inconsistent behavior java-8 stream?

查看:22
本文介绍了搜索不一致行为 java-8 流的示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 8 文档中(doc 订单流),可以看到这一点:

In java 8 documentation (doc order stream), one can see this :

如果 [a stream] 没有排序,重复执行可能会产生不同的结果.

if [a stream] is not ordered, repeated execution might produce different results.

我的问题很简单:有没有一种简单的方法可以在一个小的单元测试中说明这个事实(也许使用 HashMap 或类似的东西)?

my question is quite simple : is there an easy way to illustrate this fact in a little unit test (maybe with an HashMap or some thing like this) ?

全文在这里:

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

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.

因此,我的问题是关于严格顺序而非并行执行的.我正在质疑的就是这个案例.

Thus, my question is about a strictly sequential not parallele execution. It is this case that I'm questioning about.

推荐答案

显而易见的答案是,无论何时使用 unordered 都应该得到不同的结果.例如使用这个:

The obvious answer is that whenever you use unordered you should get different results. For example using this:

int first = Arrays.asList(1, 2, 3, 4).stream()
           .unordered()
           .parallel()
           .findFirst()
           .get();
System.out.println(first);

应该产生一个总是1的结果.因为流是无序的,所以[1,2,3,4]之外的任何结果都是可能的.

should produce a result that is not always 1. Because the stream is unordered, so any result out of [1,2,3,4] is possible.

在 java-8 中这是不正确的,流管道不会考虑 unordered :

In java-8 this is not true, the stream pipeline does not take that unordered into account:

    @Override
    public <P_IN> O evaluateParallel(PipelineHelper<T> helper,
                                     Spliterator<P_IN> spliterator) {
        return new FindTask<>(this, helper, spliterator).invoke();
    }

但是在 java-9 中情况发生了变化:

But things have change in java-9:

    @Override
    public <P_IN> O evaluateParallel(PipelineHelper<T> helper,
                                     Spliterator<P_IN> spliterator) {
        // This takes into account the upstream ops flags and the terminal
        // op flags and therefore takes into account findFirst or findAny
        boolean mustFindFirst = StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags());
        return new FindTask<>(this, mustFindFirst, helper, spliterator).invoke();
    }

所以在java-9下多次运行相同的代码会产生不同的结果.

So running the same code under java-9 multiple times will produce a different result.

有些操作已经unordered,如Stream#generateStream#forEach.

There are operations that are already unordered like Stream#generate and Stream#forEach.

这篇关于搜索不一致行为 java-8 流的示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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