vic*_*cky 7 java java-8 java-stream
我是Java 8的新手.我正在学习stream 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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
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]
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么组合器功能没有执行意义为什么这一行:
System.out.println("List One Data: " + listOne + " List Two data: " + listTwo);
Run Code Online (Sandbox Code Playgroud)
......没有执行?
那是因为你没有使用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;
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
121 次 |
最近记录: |