我有这个结构的模型
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
最佳答案
使用 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());
关于java - 减少对象列表中的整数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37774520/