user3727540 user3727540 -4 years ago 150
Java Question

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?

Answer Source

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)
               .reduce(0.0, Double::sum);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download