3

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

Samuele Pilleri
  • 734
  • 1
  • 7
  • 17
  • How are you creating `list_of_Ts`? – alayor Jun 02 '17 at 18:19
  • @alayor It actually comes from an HashMap.entrySet() – Samuele Pilleri Jun 02 '17 at 18:23
  • @alayor That doesn't really matter. It could be passed via constructor, or created internally and filled with `void add(T e){list_of_Ts.add(e);}` method. What is important is that we can assume that we have access to `List list_of_Ts` which may contain some `T` elements. – Pshemo Jun 02 '17 at 18:24
  • duolicated with https://stackoverflow.com/questions/43429030/use-of-java-8-lambdas-with-generics – holi-java Jun 02 '17 at 18:31

1 Answers1

3

Pass in an accumulator function and the identity value as parameters:

public T sum(T identity, BinaryOperator<T> accumulator) {
  return list_of_Ts.stream().reduce(identity, accumulator);
}

Note that if you want to avoid having to pass these in when you actually call it, you can create static methods to do 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.
Andy Turner
  • 137,514
  • 11
  • 162
  • 243