Java 8 stream - sum of objects

核能气质少年 提交于 2019-12-22 01:28:23

问题


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.


回答1:


What you have is a reduction:

return objects.stream().reduce(T::add).orElse(null);



回答2:


list.stream().reduce(Summable::add);

interface Summable {
    Summable add(Summable o1);
}


来源:https://stackoverflow.com/questions/30019287/java-8-stream-sum-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!