簡體   English   中英

減少對象列表中的整數屬性

[英]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));

如果我想一次找出所有模型的屬性總和,有什么方法可以實現?

輸出應該是這樣的

  • firstCount的總和= 60
  • secondCount的總和= 80
  • thirdCount的總和= 100
  • thirdCount的總和= 120

使用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)返回的新實例MyModel並使用reduce的方法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();

具有身份

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM