java8 reduce 三个参数_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 <I, O> List<O> map(Stream<I> stream, Function<I, O> mapper) {

return stream.reduce(new ArrayList<O>(), (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<O> newAcc = new ArrayList<>(acc);

newAcc.add(mapper.apply(x));

return newAcc;

}, (List<O> left, List<O> right) -> {

// We are copying left to new list to avoid mutating it.

List<O> newLeft = new ArrayList<>(left);

newLeft.addAll(right);

return newLeft;

});

}

}

下面是文档的说明,仍然不明白。。。

<U> U reduce(U identity,

BiFunction<U,? super T,U> accumulator,

BinaryOperator<U> 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)

望指教,谢谢!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值