java - 关于 Characteristics.UNORDERED in action book 中 Java 8 的困惑

标签 java java-8 java-stream

java 8 in action 的作者写了这个类:

class ToListCollector<T> implements Collector<T, List<T>, List<T>> {

    @Override
    public Supplier<List<T>> supplier() {
        return ArrayList::new;
    }

    @Override
    public BiConsumer<List<T>, T> accumulator() {
        return List::add;
    }

    @Override
    public BinaryOperator<List<T>> combiner() {
        return (l1, l2) -> {
            l1.addAll(l2);
            return l1;
        };
    }

    @Override
    public Function<List<T>, List<T>> finisher() {
        return Function.identity();
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH, Characteristics.CONCURRENT));
    }
}

然后他谈到了 Characteristic 枚举中不同值的含义。然后他解释了为什么他写的这个收集器是 IDENTITY_FINISH 和 CONCURRENT 而不是 UNORDERED,他说:

The ToListCollector developed so far is IDENTITY_FINISH, because the List used to accumulate the elements in the stream is already the expected final result and doesn’t need any further transformation, but it isn’t UNORDERED because if you apply it to an ordered stream you want this ordering to be preserved in the resulting List. Finally, it’s CONCURRENT, but following what we just said, the stream will be processed in parallel only if its underlying data source is unordered.

为什么仅当底层源是无序的时才会并行处理流?我认为它仍将并行处理,但 combiner() 必须保持顺序。是书上的错误吗?

我认为 Brian Goetz 在 this post 中非常清楚地谈到了有序流的并行处理。在最后一段中。

这本书的页数是 192 - 193。

最佳答案

那是完全错误的。即使在此处添加 CONCURRENT 特性也是错误的,因为您需要在 Supplier 中使用线程安全的数据结构。

关于java - 关于 Characteristics.UNORDERED in action book 中 Java 8 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50625544/

相关文章:

java - EasyMock 捕获可变参数(集合)

lambda - 如何在以下示例中使用 lambda 表达式和流?

Java 8 toMap 用于映射 <string, Collection<String>>

java - 如果值为 null,则从 Java 流中过滤值

java - 有没有办法以编程方式从计算机访问短信?

java - 当相应设置 target 和 min sdk 时,为什么 LayoutParams.MATCH_PARENT 没有运行时异常?

Java String 将 '&' 替换为 & 而不是 & 为 &amp;

lambda - Java 8 构造函数引用的类型是什么?

c# - 我应该学习 C# 还是 C++?

java - 按元素将列表拆分为 block