【问题标题】:Why is the reduce combiner function not executed? [duplicate]为什么没有执行reduce组合器功能? [复制]
【发布时间】:2017-08-30 08:34:55
【问题描述】:

我是 Java 8 的新手。我正在学习流 API 的 reduce 方法。我看到这段代码有一个奇怪的行为:

public class PrdefinedCollectors {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
        List<Integer> dataHolder = new ArrayList<Integer>();
        List<Integer> numbers = stream.reduce(dataHolder, 
            (List<Integer> dataStore, Integer data) -> {
                    System.out.println(data + " ->: " + dataStore);
                    dataStore.add(data);
                    return dataStore;
                },
            (List<Integer> listOne, List<Integer> listTwo) -> {
                    System.out.println("ListOne Data :" + listOne + " List Two data :" + listTwo);
                    listOne.addAll(listTwo);
                    return listOne;
                });

        System.out.println(numbers);
    }
}

输出:

1 ->: []
2 ->: [1]
3 ->: [1, 2]
4 ->: [1, 2, 3]
5 ->: [1, 2, 3, 4]
6 ->: [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]

我的问题是为什么组合器函数没有执行意味着为什么这一行:

System.out.println("List One Data: " + listOne + " List Two data: " + listTwo);

...没有被执行?

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    那是因为你没有使用parallelStream()

    combiner为并行流调用。

    但这不是您代码中的唯一问题,reduce 假设可以使用 不可变 数据 - 您的代码,按照现在的方式,对于并行流将失败。这适用于collect,但对于reduce,您需要将其更改为:

     List<Integer> numbers = stream
                .parallel()
                .reduce(
                        new ArrayList<>(),
                        (list, data) -> {
                            ArrayList<Integer> newList = new ArrayList<>(list);
                            newList.add(data);
                            return newList;
                        },
    
                        (left, right) -> {
                            ArrayList<Integer> newList = new ArrayList<>(left);
                            newList.addAll(right);
                            return newList;
                        });
    

    【讨论】:

    • 稍微改写了您的答案以使其更清楚。如果您不喜欢我猜的更改,您知道如何撤消。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2014-10-25
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多