Java8 reduce操作

首先我们看什么是reduce 模式:

Object accumulator = initialValue;

for (Object element : collection )

        accumulator = combine (accumulator ,element );

return accumulator;

首先给累积器赋初值,然后遍历目标集合,使得每一个元素与累积器做运算,得到的结果刷新累积器,遍历完成,返回累积器中的结果。这就是reduce 模式。

仔细想想,max 和 min,从集合中获得最大值,最小值也可以使用reduce 模式实现。


下面我们看一下 java8 提供的reduce 接口,在stream.class 中,提供了三种形式的reduce 操作:

Optional<T> reduce (BinaryOperator<T> accumulator);

<U> U reduce(U identity,   BiFunction<U,? super T, U> accumulator, BinaryOperator<U> combiner);

T reduce(T identity ,  BinaryOperator<T> accumulator);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容