Generalize the method

I got this method

public static Integer addCollectionElements(List<Integer> list) {
    return list.stream().reduce(0, Integer::sum).intValue();
} 

      

which I would like to generalize to any class that implements the sum of a method (like Float).

Can this be achieved using Java Generics?

+3


source to share


2 answers


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();
}

      

+5


source


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.

+4


source







All Articles