【问题标题】:Reducing integer attributes in a list of objects减少对象列表中的整数属性
【发布时间】:2016-10-12 23:21:00
【问题描述】:

我有这个结构的模型

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

【问题讨论】:

  • 你的意思是long collect = modelList.stream().mapToLong(MyModel::getFirstCount).sum();?除非您有一个不能多次遍历的特殊流源(在您的示例中不是这种情况),否则执行如上所示的四个操作是最简单且(在大多数情况下)最有效的解决方案。

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


【解决方案1】:

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

【讨论】:

  • @OP 或者,您可以在 MyModel 上创建一个 add(MyModel) 方法。这会将传递的模型的值添加到this 模型,然后返回this。这将使第二个参数(a, b) -&gt; a.add(b),而无需分配新对象。
【解决方案2】:

你可以做的是创建一个方法add(MyModel),它返回一个MyModel的新实例,并使用Streamreduce方法以及@OverridetoString()

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

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2011-11-04
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多