带有sorted()的java 8 parallelStream() [英] java 8 parallelStream() with sorted()

查看:1077
本文介绍了带有sorted()的java 8 parallelStream()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JDK 8 EA现在已经出局了,我只是想习惯lambda和新的Stream API。我试图用并行流对列表进行排序,但结果总是错误的:

JDK 8 EA is out now, and I am just trying to get used to the lambda and the new Stream API. I've tried to sort a list with parallel stream, but the result is always wrong:

import java.util.ArrayList;
import java.util.List;

public class Test
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("C");
        list.add("H");
        list.add("A");
        list.add("A");
        list.add("B");
        list.add("F");
        list.add("");

        list.parallelStream() // in parallel, not just concurrently!
            .filter(s -> !s.isEmpty()) // remove empty strings
            .distinct() // remove duplicates
            .sorted() // sort them
            .forEach(s -> System.out.println(s)); // print each item
    }
}

输出:

C
F
B
H
A

请注意,每次输出都不同。我的问题是,这是一个错误吗?或者不可能并行排序列表?如果是这样,那么为什么JavaDoc没有声明呢?最后一个问题,还有另一个操作,其输出会根据流类型而有所不同吗?

Note that each time the output is different. My questions is, is it a bug? or is it not possible to sort a list in parallel? if so, then why the JavaDoc doesn't state that? Last question, is there another operation whose output would differ depending on the stream type?

推荐答案

您需要使用 forEachOrdered ,而不是 forEach

根据 forEach doc:


对于并行流管道,此操作不保证尊重遭遇顺序因为这样做会牺牲并行性的好处。对于任何给定元素,可以在任何时间以及库选择的任何线程中执行该动作。如果操作访问共享状态,则它负责提供所需的同步。

For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.

这篇关于带有sorted()的java 8 parallelStream()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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