Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 255
user3727540 Avatar asked Jul 25 '26 15:07

user3727540


1 Answers

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();
}
like image 130
Mureinik Avatar answered Jul 27 '26 05:07

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!