如何在java中对BigDecimal属性求和

avkwfej4  于 2023-01-07  发布在  Java
关注(0)|答案(5)|浏览(226)

让我们举一个简单的例子:

Class Foo{
     private BigDecimal item1;
     private BigDecimal item2;
     private BigDecimal item3;
     private BigDecimal item4;
     private BigDecimal item5;
//setters and getters
   public BigDecimal getTotal(){
       BigDecimal total = BigDecimal.ZERO;
        if(null != item1){
            total =total .add(item1);
           }
        if(null != item2){
            total =total .add(item2);
           }
          ...
          ...
}
    }

我是在实体层次上求和,这是不是正确的方法?
有谁能给予我更好的代码来获取总价值

jdgnovmf

jdgnovmf1#

您可以使用循环来简化代码:

import java.util.Arrays;

...

public BigDecimal getTotal(){
   BigDecimal total = BigDecimal.ZERO; 
   for(BigDecimal bd: Arrays.asList(item1,item2,item3,item4,item5)){
        if(null != bd){
            total =total .add(bd);
           }
    }
}
cwtwac6a

cwtwac6a2#

使用List<BigDecimal>

public BigDecimal getTotal(){
    List<BigDecimal> values =  Arrays.asList(item1, item2, item3, item4, item5)

    BigDecimal total = BigDecimal.ZERO;
    for (BigDecimal value : values) {
        if(value != null) {
            total = total.add(value);
        }
    }
    return total;
}
svgewumm

svgewumm3#

如果你有一个固定的(和少量的)数字,你可以做如下:

total = total.add(item1 ==null ? BigDecimal.ZERO : item1).add(item2 ==null ? BigDecimal.ZERO : item2).add(item3 ==null ? BigDecimal.ZERO : item3);

如果项目为null,则添加0,否则添加项目本身。如果项目的数量可变,则需要在数组中迭代它们,或者类似于以下操作:

for (BigDecimal current : myBigDecimalArray){
   total = total.add(current ==null ? BigDecimal.ZERO : current );
}
wz3gfoph

wz3gfoph4#

如果您不介意使用反射:

public static BigDecimal sum(Object instance, String... fields) {
    BigDecimal total = BigDecimal.ZERO;
    for (String field : fields) {
        BigDecimal value = getProperty(instance, field);
        if (value != null) {
            total = total.add(value);
        }
    }
    return total;
}

样品:

annex.setOrTot(ReflectionUtils.sum(annex, "orEstadoOrg", "orSs", "orCcaa", "orCorpLoc", "orResto"));
    annex.setIdpTot(ReflectionUtils.sum(annex, "idpEstadoOrg", "idpSs", "idpCcaa", "idpCorpLoc", "idpResto"));
    annex.setDrTot(ReflectionUtils.sum(annex, "drEstadoOrg", "drSs", "drCcaa", "drCorPloc", "drResto"));
    annex.setIdcTot(ReflectionUtils.sum(annex, "idcEstadoOrg", "idcSS", "idcCcaa", "idcCorPloc", "idCresto"));
jfgube3f

jfgube3f5#

java 8+,可以使用流API

BigDecimal total = itemList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

相关问题