首先我們看什么是reduce 模式:
Object accumulator = initialValue;
for (Object element : collection )
? ? ? ? accumulator = combine (accumulator ,element );
return accumulator;
首先給累積器賦初值,然后遍歷目標集合,使得每一個元素與累積器做運算,得到的結果刷新累積器,遍歷完成,返回累積器中的結果。這就是reduce 模式。
仔細想想,max 和 min,從集合中獲得最大值,最小值也可以使用reduce 模式實現(xiàn)。
下面我們看一下 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);