I would like to generically add numbers in java. I\'m running into difficulty because the Numbers class doesn\'t really support what I want to do. What I\'ve tried so far
since the introduction of Java 8 streams and lambda you can have a shorter solution
public interface Adder {
static E sumValues(Collection objectsToSum, BinaryOperator sumOp) {
return objectsToSum.stream().reduce(sumOp).orElse(null);
}
}
and use it as follows
int sum = Adder.sumValues(List.of(4, 5, 6, 7), Integer::sum);
Note, that Stream::reduce
with just accumulator returns Optional
that's why I used orElse(null)
, but I would recommend to send also zero value as parameter to Adder::sumValue