How to sum total numbers in java
I have the following scenario:
class MyListOfNumbers<T extends Number & Comparable<T>>
{
public T sum()
{
return list_of_Ts.stream()
.sum();
}
}
I don't know (specifically) anything about the T other than the number, and it can be compared to "siblings" (needed to sort stuff ...).
Obviously this won't work and it won't work old-Java style (i.e. loops) because you just can't, as far as I know, do T x = 0
.
None of these will work as I think the same reason and the fact that T does not implement the sum; also, I read that it won't work on empty sets.
class MyListOfNumbers<T extends Number & Comparable<T>>
{
public T sum()
{
return list_of_Ts.stream()
.reduce(0, T::sum);
}
}
Then how to do it?
EDIT : please consider that T could be anything from a byte to BigDecimal and forcing it to an integer could mean data loss
source to share
Pass the accumulator function and id value as parameters:
public T sum(T identity, BinaryOperator<T> accumulator) {
return list_of_Ts.stream().reduce(identity, accumulator);
}
Note that if you don't want to pass them when you actually call it, you can create static methods to make the call:
public static int intSum(MyListOfNumbers<Integer> list) {
return list.sum(0, (a, b) -> a + b);
}
public static double doubleSum(MyListOfNumbers<Double> list) {
return list.sum(0, (a, b) -> a + b);
}
// etc.
source to share