18

Let's say I have a list of objects implementing below interface:

public interface Summable<T> {
    T add(T o1);
}

Let's say I have also some class which is able to sum these objects:

public class Calculator<T extends Summable<T>> {
    public T sum(final List<T> objects) {
        if (null == objects) {
            throw new IllegalArgumentException("Ups, list of objects cannot be null!");
        }
        T resultObject = null;
        for (T object : objects) {
            resultObject = object.add(resultObject);
        }
        return resultObject;
   }
}

How can I achieve the same using Java 8 streams?

I'm playing around a custom Collector, but couldn't figure out some neat solution.

JabberwockyDecompiler
  • 3,318
  • 2
  • 42
  • 54
Piotr Kozlowski
  • 899
  • 1
  • 13
  • 25

2 Answers2

25

What you have is a reduction:

return objects.stream().reduce(T::add).orElse(null);
Radiodef
  • 37,180
  • 14
  • 90
  • 125
2
list.stream().reduce(Summable::add);

interface Summable {
    Summable add(Summable o1);
}
user2418306
  • 2,352
  • 1
  • 22
  • 33