java8中3个参数的reduce方法怎么理解?
例如这个练习题,使用reduce和lambda表达式来实现map。
不明白的是reduce第三个参数的意义,感觉多此一举
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
public class MapUsingReduce {
public static List map(Stream stream, Function mapper) {
return stream.reduce(new ArrayList(), (acc, x) -> {
// We are copying data from acc to new list instance. It is very inefficient,
// but contract of Stream.reduce method requires that accumulator function does
// not mutate its arguments.
// Stream.collect method could be used to implement more efficient mutable reduction,
// but this exercise asks to use reduce method.
List newAcc = new ArrayList<>(acc);
newAcc.add(mapper.apply(x));
return newAcc;
}, (List left, List right) -> {
// We are copying left to new list to avoid mutating it.
List newLeft = new ArrayList<>(left);
newLeft.addAll(right);
return newLeft;
});
}
}
下面是文档的说明,仍然不明白。。。
U reduce(U identity,
BiFunction accumulator,
BinaryOperator combiner)
Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions. This is equivalent to:
U result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;
but is not constrained to execute sequentially.
The identity value must be an identity for the combiner function. This means that for all u, combiner(identity, u) is equal to u. Additionally, the combiner function must be compatible with the accumulator function; for all u and t, the following must hold:
combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)
望指教,谢谢!
相关阅读:
angular指令获取指令模板中的元素
PHP实现插件机制中变量作用域的问题
yii2 如何生成如下的HTML表单?
PHP 怎么列出来某一个日期距离现在的日期
input元素使用outline做边框,选中时会缩小?
电脑浏览器和手机浏览器视频在线播放兼容问题?
静态变量/方法问题
Mysql创建数据库时提示Error 1044
初学,请问当我处理多个label的时候能不能统一处理宽高,不用每次去指定rect?
有没有比Mathjax更轻量的js数学公式渲染库?
spawn expect 无正常输出
火狐浏览器不能正确执行$(window).on('scroll', function(){})?
一个关于IE版本HACK的问题
求路过的做过CLRS的神犇看一眼习题11.3-3谢谢
git库整合
myeclipse内置浏览器 显示空白?
JavaScipt中正则表达式对象exec方法是如何匹配的?
JS如何判断某个对象的属性是不是一个函数?
css怎样清除*{font-size:14px;font-family:'Microsoft Yahei'}
如何将html源代码显示在html中?