how to sum generic numbers in java

Viewed 997

I have the following scenario:

class MyListOfNumbers<T extends Number & Comparable<T>>
{
    public T sum()
    {
        return list_of_Ts.stream()
        .sum();
    }
}

I know nothing (on purpose) about T except it is a number and it can be compared to "siblings" (needed for sorting stuff...).

Obviously this doesn't work and it won't work in an old-Java fashion (ie. loops) because you simply can't, as far as I know, do T x = 0.

Neither this will work for I think the same reason and the fact that T doesn't implement sum; moreover I read it wouldn'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 that?

EDIT: please consider T can be anything from Byte to a BigDecimal and forcing it to a integer might mean loosing data

1 Answers
Related