有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个这种结构的模型

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
  • 二次计数之和=80
  • 第三个总数=100
  • 第四计数之和=120

共 (2) 个答案

  1. # 1 楼答案

    您可以创建一个方法add(MyModel),返回MyModel的一个新实例,并使用Streamreduce方法以及@Override{}

    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();
    
  2. # 2 楼答案

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