java - 为什么永远无法达到收集方法中的此 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);
解决方案
仅当您并行调用流处理管道时才会调用组合器函数。因此,将其更改为并行流,然后它应该到达组合器功能。所以这应该触发它。
people.parallelStream()...
例如,假设有 2 个工作线程处理此工作负载。任何并行执行都涉及将源分成几部分,同时执行它们,最后将部分结果合并到一个结果容器中。每个线程 T1 和 T2 都有一个关联的 List,因此容器是线程受限的。accumulator 函数将每个单个元素添加到关联的容器中。线程 T1 和 T2 都完成后,部分容器应合并到一个大型结果容器中。这就是组合器功能发挥作用的地方。在串行执行中,不涉及这样的结果合并,因此组合器在那里没有用处。
推荐阅读
- java - 将同名 xml 节点添加到 arrayList
- node.js - 提供数据处理的进展
- php - 无法再次获得 .htaccess 工作
- java - 如何使用我的正则表达式匹配多次出现?
- python - 我有一个清单,我需要在每一行打印出 10 个项目?
- c++ - OpenMP 任务等待不工作
- c# - 无法创建跨平台 ARCore 会话 (ErrorInvalidArgument)。GoogleARCoreInternal.ARCoreIOSLifecycleManager:EnableSession()
- javascript - 使用(引导)HTML 和纯 Javascript 创建待办事项列表
- c - 为什么 for 循环终止但其中的 memcpy 复制相同的子字符串?
- laravel - 在laravel中使用数组过滤集合