Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream - sum of objects

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.

like image 806
Piotr Kozlowski Avatar asked May 03 '15 20:05

Piotr Kozlowski


People also ask

How do you sum an object in Java?

Using Stream.collect() asList(1, 2, 3, 4, 5); Integer sum = integers. stream() . collect(Collectors. summingInt(Integer::intValue));

How do you sum a List in Java?

A simple solution to calculate the sum of all elements in a List is to convert it into IntStream and call sum() to get the sum of elements in the stream. There are several ways to get IntStream from Stream<Integer> using mapToInt() method.


1 Answers

What you have is a reduction:

return objects.stream().reduce(T::add).orElse(null);
like image 76
Radiodef Avatar answered Oct 04 '22 01:10

Radiodef