sdicola
sdicola

Reputation: 962

Generalise a 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 generalise to any class that implements the method sum (e.g. Float).

Is it possible to achieve this by using Java Generics?

Upvotes: 3

Views: 186

Answers (2)

Mureinik
Mureinik

Reputation: 311883

Unfortunately, the Number base class doesn't have a sum method, so you can't do this directly. What you could do, however, is call doubleValue() on each Number you receive, and sum them as a doubles:

public static double addCollectionElements(List<? extends Number> list){
    return list.stream().mapToDouble(Number::doubleValue).sum();
}

Upvotes: 5

Justas
Justas

Reputation: 811

Integer.sum() is just a static method which can be used as a BinaryOperator. There is no way to make it "generic for objects that have a method sum". What you can do is add two more arguments to the method, where you provide your own sum function and an initial value - zero in your case. An extreme example would be this:

public static <T extends Number> T addCollectionElements(List<T> list, T initialValue, BinaryOperator<T> sumFunction){
    return list.stream().reduce(initialValue, sumFunction);
}

Invocation would look like this:

addCollectionElements(list, 0, Integer::sum);

But I do not believe you would gain anything by doing this.

Upvotes: 4

Related Questions