0

I have a list that has to accept either a list of Integer/Double/Float/Long and return the sum. I tried this

public static Number getSum(List< ? extends Number> lst) {
    return lst.stream().reduce(0.0, (a, b) -> a+b);
}

But I am getting this error in compile time

The operator + is undefined for the argument type(s) capture#3-of ? extends java.lang.Number, capture#3-of ? extends java.lang.Number
sovan
  • 363
  • 1
  • 4
  • 13
  • 2
    You cant add two Numbers without knowing if they are integer, long, or double etc. If they are all real numbers, use doubleValue() – SwiftMango Nov 26 '20 at 05:44
  • You can try to use reflection in order to get the static `sum` method. You can then call it using the parameters. However, this only works if both have the same type and the type has the `sum` method. – dan1st Nov 26 '20 at 06:52
  • Does this answer your question? [How to add two java.lang.Numbers?](https://stackoverflow.com/questions/2721390/how-to-add-two-java-lang-numbers) – dan1st Nov 26 '20 at 08:52

1 Answers1

0

There can be a custom subclass of Number, that cannot be applied to +. E.g. you declared a class Natural

class Natural extends Number {
    ...
}

You can't add it using plus operator.

So I think the best you can to is to cast them to double first.

public static Number getSum(List< ? extends Number> lst) {
    return lst.stream().mapToDouble(Number::doubleValue).sum();
}
Dmitry Barskov
  • 1,200
  • 8
  • 14