我有一个整数流,流的来源是一个列表:[3, 27]
.
做的时候list.stream.reduce(1, (a,b) -> a/b))
,如何让reduce除以3/1 = 3然后27/3 = 9并返回9?
最佳答案
一不应该用reduce
具有不是 associative 的累加器功能.这在 JDK documentation of the API 中得到了特别强调。以及。
The accumulator function must be an associative function.
你真的不需要依赖流来进行这种操作,事实上,流在持久化中间状态方面并不好(在这种情况下),所以一个简单的 for 循环解决方案应该适合你:
int reduce = 1;
for (Integer integer : List.of(3, 27)) {
reduce = integer / reduce;
}
System.out.println(reduce);
要测试出于此目的使用流 API 的不一致之处,只需将代码更改为以下内容并注意输出!Integer reduce = List.of(3, 7).parallelStream().reduce(1, (a, b) -> b / a);
System.out.println(reduce);
关于java - 如何让 `reduce` 将流中的值彼此相除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62989174/