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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With