Generalize the method
Unfortunately, the base class Number
does not have a method sum
, so you cannot do this directly. However, you can make a call doubleValue()
to each one Number
you receive and sum them up as a doubling:
public static double addCollectionElements(List<? extends Number> list){
return list.stream().mapToDouble(Number::doubleValue).sum();
}
source to share
Integer.sum()
is just a static method that can be used like BinaryOperator
. There is no way to make it "common to objects that have a method sum
". What you can do is add two more arguments to the method, where you provide your own function sum
and the initial value is zero in your case. An extreme example would be the following:
public static <T extends Number> T addCollectionElements(List<T> list, T initialValue, BinaryOperator<T> sumFunction){
return list.stream().reduce(initialValue, sumFunction);
}
The call will look like this:
addCollectionElements(list, 0, Integer::sum);
But I do not believe that you will win anything by doing this.
source to share