java 8 parallelStream() 与 sorted() [英] java 8 parallelStream() with sorted()

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

问题描述

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 文档:

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

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.

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

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