它的工作原理:BigDecimal Sum with Reduce和BigDecimal :: add

Eng*_* Re 6 java lambda java-8 java-stream functional-interface

我可以理解为什么计算Total1,但是当计算Total2时我不知道!如何在BiFunction中使用BigDecimal :: add?签名不一样!!!

package br.com.jorge.java8.streams.bigdecimal;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class BigDecimalSumTest {
    public static void main(String[] args) {

        List<BigDecimal> list = new ArrayList<>();

        list.add(new BigDecimal("1"));
        list.add(new BigDecimal("2"));

        BigDecimal total1 = list.stream().reduce(BigDecimal.ZERO, (t, v) -> t.add(v));

        BigDecimal total2 = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        System.out.println("Total 1: " + total1);
        System.out.println("Total 2: " + total2);
    }
}
Run Code Online (Sandbox Code Playgroud)

Nam*_*man 8

BinaryOperator<T>在您当前的上下文中用作.

它的等效lambda表示:

(bigDecimal, augend) -> bigDecimal.add(augend) // same as in your previous line of code
Run Code Online (Sandbox Code Playgroud)

和匿名类表示:

new BinaryOperator<BigDecimal>() {
    @Override
    public BigDecimal apply(BigDecimal bigDecimal, BigDecimal augend) {
        return bigDecimal.add(augend);
    }
}
Run Code Online (Sandbox Code Playgroud)

其中BinaryOperator<T> extends BiFunction<T,T,T>,意味着它BiFunction操作数和结果都是相同类型的情况下的特殊化.

除此之外,您的代码实际上正在使用reduce方法的重载实现之一,即Stream.reduce(T identity, BinaryOperator<T> accumulator).


如何在BiFunction中使用BigDecimal :: add

只需一步,只为解释,也有一个重载的实现,它使用combinerStream.reduce?(U identity, BiFunction<U,?? super T,?U> accumulator, BinaryOperator<U> combiner)其中将如下所示:

BigDecimal total = list.stream()
                       .reduce(BigDecimal.ZERO, BigDecimal::add, BigDecimal::add);
//                                                   ^^                ^^
//                                              BiFunction here    BinaryOperator here
Run Code Online (Sandbox Code Playgroud)