Reputation: 613
Let's get a simple example:
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);
}
...
...
}
}
I am summing in entity level. this is correct way or not?
can any one give me better code for getting total Value
Upvotes: 3
Views: 17089
Reputation: 11
java 8+, could use stream api
BigDecimal total = itemList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
Upvotes: 0
Reputation: 1973
If you don't mind using reflection:
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;
}
Sample:
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"));
Upvotes: 0
Reputation: 3190
You can use a loop to make your code simple :
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);
}
}
}
Upvotes: 3
Reputation: 51353
Use a 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;
}
Upvotes: 3
Reputation: 7928
If you have a fixed (and little) amount of numbers you can do as follows:
total = total.add(item1 ==null ? BigDecimal.ZERO : item1).add(item2 ==null ? BigDecimal.ZERO : item2).add(item3 ==null ? BigDecimal.ZERO : item3);
Adding 0 if the item is null and the item itself otherwise. IF you have a variable amount of items, then you need to iterate over them in a array or something like this:
for (BigDecimal current : myBigDecimalArray){
total = total.add(current ==null ? BigDecimal.ZERO : current );
}
Upvotes: 0