我有这个结构的模型
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));
如果我想在一次传递中找出所有模型中的属性总和怎么办?有什么方法可以实现这个目标吗?
输出应该是
答案 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();