iterative sum bigdecimal

0

I have a ArrayList whose one of the fields is BigDecimal . I can not do this sum iteratively with a loop. Can anyone give a tip on how to perform this operation?
If it were a% common%, it would do the following, but using the bigdecimal, I can not think of a solution:

for(..){
    valorTotal += lista.get(i).getValorItem(); 
}
    
asked by anonymous 04.08.2016 / 15:51

1 answer

5

Adriano, in% with% it is impossible to use the BigDecimal operator. Use + :

valorTotal = BigDecimal.ZERO;

for (...) {
    valorTotal = valorTotal.add(lista.get(i).getValorItem());
}

If you are in Java 8, you can use add() (very cool):

valorTotal = lista.stream()
    .map(NomeDaSuaClasse::getValorItem)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
    
04.08.2016 / 16:08