为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MMMHUHU 2023-08-04 15:29:56
我有一个具有多个整数属性的类,如下所示: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;这个实现工作正常,但我现在想是否有一种更简单的方法来做到这一点,清理这段代码并使其变得简单
查看完整描述

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;

}


查看完整回答
反对 回复 2023-08-04
?
慕莱坞森

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

}

另一个好处是可以更立即清楚地了解循环正在做什么。


查看完整回答
反对 回复 2023-08-04
?
桃花长相依

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


查看完整回答
反对 回复 2023-08-04
?
holdtom

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;


查看完整回答
反对 回复 2023-08-04
  • 4 回答
  • 0 关注
  • 133 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信