简介

reduce()用于从一个序列中,通过对其中元素反复执行一个“合并”操作,最终得到一个结果。

方法签名

有三种:

  1. Optional<T> reduce(BinaryOperator<T> accumulator);
  2. T reduce(T identity, BinaryOperator<T> accumulator);
  3. <U> U reduce(U identity,
  4. BiFunction<U, ? super T, U> accumulator,
  5. BinaryOperator<U> combiner);

参数解析:

  • Identity:reduce操作的初始值。另外如果序列是空的,则Identity作为结果返回。
  • accumulator:一个接收两个参数的函数,第一个参数是目前reduce的中间结果,第二个参数是当前待处理的序列元素。
  • combiner:combiner用于合并两个中间结果。应用场合有二:
    • 当steam是并行流时,序列的各个部分将同时进行reduce操作,产生多个中间结果。combiner负责将这些中间结果合并为最终结果。
    • 当reduce操作的返回结果和序列中元素不是同一个类型时,需要使用combiner来合并中间结果(为什么会如此设计?)。

参考资料

https://www.baeldung.com/java-stream-reduce