Iterative sum bigdecimal

Asked

Viewed 1,956 times

0

I have a ArrayList one of the fields is a BigDecimal. I am not able to make this sum iteratively with loop. Someone can give a hint of how to perform this operation?
If it were a double common, would do the form below, but using bigdecimal, I can’t think of a solution:

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

1 answer

5


Adriano, in the BigDecimal it is impossible to use the operator +. Use add():

valorTotal = BigDecimal.ZERO;

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

If you’re on Java 8, you can use it stream (nicely):

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.