对列表中的所有属性值求和

我有一个具有多个整数属性的类,如下所示:


public class Test {

    private Integer a;

    private Integer b;

    private Integer c;

    private Integer d;

    private Integer e;

    private Integer f;

    private Integer g;

}

因此,我得到了一个包含很多寄存器的类的列表,并且我必须单独求和该列表的所有属性。然后我做了类似的事情:


List<Test> tests = testRepository.findAllTest();


Test test = new Test();

for (Test testList: tests) {

    test.setA(test.getA + testList.getA);

    test.setB(test.getB + testList.getB);

    test.setC(test.getC + testList.getC);

    test.setD(test.getD + testList.getD);

    test.setE(test.getE + testList.getE);

    test.setF(test.getF + testList.getF);

    test.setG(test.getG + testList.getG);

}

 return test;

这个实现工作正常,但我现在想是否有一种更简单的方法来做到这一点,清理这段代码并使其变得简单


MMMHUHU
浏览 139回答 4
4回答

猛跑小猪

您可以修改您的 Test 类以包含添加方法:public class Test {&nbsp; &nbsp; private int a;&nbsp; &nbsp; private int b;&nbsp; &nbsp; private int c;&nbsp; &nbsp; //...&nbsp; &nbsp; public void add(Test o) {&nbsp; &nbsp; &nbsp; &nbsp; this.a += o.getA();&nbsp; &nbsp; &nbsp; &nbsp; this.b += o.getB();&nbsp; &nbsp; &nbsp; &nbsp; this.c += o.getC();&nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; }&nbsp; &nbsp; // setters and getters...}那么你的求和函数可以如下所示:public Test summation(Collection<Test> testCollection) {&nbsp; &nbsp; Test sum = new Test();&nbsp; &nbsp; for(Test test : testCollection) {&nbsp; &nbsp; &nbsp; &nbsp; sum.add(test);&nbsp; &nbsp; }&nbsp; &nbsp; return sum;}

慕莱坞森

我会将其分解为几个子问题:将一个测试对象添加到另一个测试对象,然后总结列表。对于第一个问题,您可以向 Test 类添加一个方法,该方法将两个测试对象相加并返回一个包含总和的新 Test 对象。public class Test {&nbsp; &nbsp; ...&nbsp; &nbsp; public Test add(Test testToAdd){&nbsp; &nbsp; &nbsp; &nbsp; Test result = new Test();&nbsp; &nbsp; &nbsp; &nbsp; result.setA(a + testToAdd.getA());&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; result.setG(g + testToAdd.getG());&nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; }}然后你可以在求和循环中调用它:List<Test> tests = testRepository.findAllTest();Test testTotal = new Test();for (Test test: tests) {&nbsp; &nbsp; testTotal = testTotal.add(test);}另一个好处是可以更立即清楚地了解循环正在做什么。

桃花长相依

要使用以下命令向现有答案添加另一种类似的方法Stream.reduce:向您的测试类添加一个无参数构造函数(如果您还没有):private Test() {&nbsp; &nbsp; this(0,0,0,0,0,0,0);}将方法 addAttributes 添加到您的测试类public Test addAttributes(Test other){&nbsp; &nbsp; this.a += other.a;&nbsp;&nbsp; &nbsp; this.b += other.b;&nbsp;&nbsp; &nbsp; this.c += other.c;&nbsp;&nbsp; &nbsp; this.d += other.d;&nbsp; &nbsp; //....&nbsp;&nbsp; &nbsp; return this;}然后,您可以通过执行以下操作来减少列表:Test result = tests.stream().reduce(new Test(), (t1,t2) -> t1.addAttributes(t2));

holdtom

在你的类中写一个add(Test other)方法Test:public void add(Test other) {&nbsp; &nbsp;this.a += other.getA();&nbsp; &nbsp;this.b += other.getB();&nbsp; &nbsp;// ...&nbsp; &nbsp;this.g += other.getG();}然后,使用它:Test test = new Test();List<Test> allTests = testRepository.findAllTest();allTests.forEach(individualTest -> individualTest.add(test));return test;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java