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

时间:2016-06-12 12:58:54

标签: java functional-programming java-8 reduction collectors

我有这个结构的模型

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));

如果我想在一次传递中找出所有模型中的属性总和怎么办?有什么方法可以实现这个目标吗?

输出应该是

  • firstCount = 60
  • 的总和
  • secondCount = 80
  • 的总和
  • thirdCount = 100
  • 的总和
  • fourthCount = 120
  • 的总和

2 个答案:

答案 0 :(得分:4)

使用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());

答案 1 :(得分:1)

您可以做的是创建一个方法add(MyModel),该方法返回MyModel的新实例,并使用reduce的{​​{1}}方法以及Stream @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();