减少对象列表中的整数属性

Reducing integer attributes in a list of objects

我有这个结构的模型

public class MyModel {
        private long firstCount;
        private long secondCount;
        private long thirdCount;
        private long fourthCount;

        public MyModel(firstCount,secondCount,thirdCount,fourthCount) 
        {
        }
        //Getters and setters

}  

假设我有一个包含以下数据的模型列表

MyModel myModel1 = new MyModel(10,20,30,40);
MyModel myModel2 = new MyModel(50,60,70,80);

List<MyModel> modelList = Arrays.asList(myModel1, myModel2);

假设我想找出所有模型中 firstCount 的总和,我可以这样做

Long collect = modelList.stream().collect
(Collectors.summingLong(MyModel::getFirstCount));

如果我想一次性找出所有模型中的属性总和怎么办?有什么办法可以实现吗?

输出应该类似于

使用MyModel作为累加器:

MyModel reduced = modelList.stream().reduce(new MyModel(0, 0, 0, 0), (a, b) ->
                      new MyModel(a.getFirstCount() + b.getFirstCount(),
                                  a.getSecondCount() + b.getSecondCount(),
                                  a.getThirdCount() + b.getThirdCount(),
                                  a.getFourthCount() + b.getFourthCount()));
System.out.println(reduced.getFirstCount());
System.out.println(reduced.getSecondCount());
System.out.println(reduced.getThirdCount());
System.out.println(reduced.getFourthCount());

你可以做的是创建一个方法 add(MyModel),returns MyModel 的一个新实例,并使用 Streamreduce 方法,并且, @Override toString()

public MyModel add(MyModel model) {
    long first = firstCount + model.getFirstCount();
    long second = secondCount + model.getSecondCount();
    long third = thirdCount + model.getThirdCount();
    long fourth = fourthCount + model.getFourthCount();


    return new MyModel(first, second, third, fourth);
}

@Override
public String toString() {
    return "sum of firstCount = " + firstCount + "\n"
        +  "sum of secondCount = " + secondCount + "\n"
        +  "sum of thirdCount = " + thirdCount + "\n"
        +  "sum of fourthCount = " + fourthCount;
}

无身份

String result = modelList.stream()
                         .reduce((one, two) -> one.add(two))
                         .orElse(new MyModel(0,0,0,0))
                         .toString();

有身份

String result = modelList.stream()
                         .reduce(new MyModel(0,0,0,0), (one, two) -> one.add(two))
                         .toString();