首页 > 解决方案 > 为什么永远无法达到收集方法中的此 BiConsumer 组合器代码?

问题描述

在 main 方法中,我制作了一个不同年龄的 Person 列表。现在当我使用 collect 方法将此列表转换为 Person 年龄列表时。BiConsumer 组合器函数中的代码永远无法到达。

class Person {
    private int age;

    public int getAge() {
        return age;
    }
}

//第二种收集方式

ArrayList<Integer> pAges = people.stream()
                            .collect(ArrayList<Integer>::new, 
                                    (listGivenBySupplier, personObjectFromPeopleStream) -> listGivenBySupplier.add(personObjectFromPeopleStream.getAge()), 
                                    (r1, r2) -> {  //Also please explain what value is passed to r1 and r2
                                            System.out.println("r1: " + r1);
                                            System.out.println("r2: " + r2);
                                            r1.add(2222);
                                            r2.add(2211); 
                            });
System.out.println("pAges:" + pAges);

标签: javajava-8java-streamcollectors

解决方案


仅当您并行调用流处理管道时才会调用组合器函数。因此,将其更改为并行流,然后它应该到达组合器功能。所以这应该触发它。

people.parallelStream()...

例如,假设有 2 个工作线程处理此工作负载。任何并行执行都涉及将源分成几部分,同时执行它们,最后将部分结果合并到一个结果容器中。每个线程 T1 和 T2 都有一个关联的 List,因此容器是线程受限的。accumulator 函数将每个单个元素添加到关联的容器中。线程 T1 和 T2 都完成后,部分容器应合并到一个大型结果容器中。这就是组合器功能发挥作用的地方。在串行执行中,不涉及这样的结果合并,因此组合器在那里没有用处。


推荐阅读