I want to create a BinaryOperator<BigInteger> biOp
in order to add up BigInteger
values. For example, I will have a huge list or array of different BigInteger
values and I want to add them all up using a loop and the biOp
.
The result for e.g. two values should look something like this:
System.out.println(biOp.apply(BigInteger.ONE, BigInteger.ONE));
// outputs 2
How do I create or initialize biOp
properly?
The simplest way is to use a method reference to BigInteger::add
:
BinaryOperator<BigInteger> binOp = BigInteger::add;
This works because when you use the class name to create a method reference to an instance method (i.e. not a static
method), the apply
method will take an extra parameter for the instance to call the method on. So although the add
method takes one BigInteger
parameter, this method reference takes two BigInteger
parameters.