4 回答

TA貢獻1858條經驗 獲得超8個贊
您可以修改您的 Test 類以包含添加方法:
public class Test {
private int a;
private int b;
private int c;
//...
public void add(Test o) {
this.a += o.getA();
this.b += o.getB();
this.c += o.getC();
//...
}
// setters and getters...
}
那么你的求和函數可以如下所示:
public Test summation(Collection<Test> testCollection) {
Test sum = new Test();
for(Test test : testCollection) {
sum.add(test);
}
return sum;
}

TA貢獻1810條經驗 獲得超4個贊
我會將其分解為幾個子問題:將一個測試對象添加到另一個測試對象,然后總結列表。
對于第一個問題,您可以向 Test 類添加一個方法,該方法將兩個測試對象相加并返回一個包含總和的新 Test 對象。
public class Test {
...
public Test add(Test testToAdd){
Test result = new Test();
result.setA(a + testToAdd.getA());
...
result.setG(g + testToAdd.getG());
return result;
}
}
然后你可以在求和循環中調用它:
List<Test> tests = testRepository.findAllTest();
Test testTotal = new Test();
for (Test test: tests) {
testTotal = testTotal.add(test);
}
另一個好處是可以更立即清楚地了解循環正在做什么。

TA貢獻1860條經驗 獲得超8個贊
要使用以下命令向現有答案添加另一種類似的方法Stream.reduce:
向您的測試類添加一個無參數構造函數(如果您還沒有):
private Test() {
this(0,0,0,0,0,0,0);
}
將方法 addAttributes 添加到您的測試類
public Test addAttributes(Test other){
this.a += other.a;
this.b += other.b;
this.c += other.c;
this.d += other.d;
//....
return this;
}
然后,您可以通過執行以下操作來減少列表:
Test result = tests.stream().reduce(new Test(), (t1,t2) -> t1.addAttributes(t2));

TA貢獻1805條經驗 獲得超10個贊
在你的類中寫一個add(Test other)方法Test:
public void add(Test other) {
this.a += other.getA();
this.b += other.getB();
// ...
this.g += other.getG();
}
然后,使用它:
Test test = new Test();
List<Test> allTests = testRepository.findAllTest();
allTests.forEach(individualTest -> individualTest.add(test));
return test;
添加回答
舉報