【发布时间】: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