Collection of an Object doing calculations with BigDecimal

-1

I have the ValueTotal attribute this value should be represented by the sum of all items in the Item class that are in the items list, I am trying to sum all items in the list that are BigDecimal, but when I execute the value is 0, that is, it is not calculating, I would understand this.

package br.com.improving.carrinho;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CarrinhoCompras {

    private  Collection<Item> items = new ArrayList<Item>();
    private BigDecimal valorTotal = BigDecimal.ZERO;

    public CarrinhoCompras(Item item) {
        items = new ArrayList<Item>();
        items.add(item);
    }

    public CarrinhoCompras() {

    }

    public void adicionarItem(Produto produto, BigDecimal valorUnitario, int quantidade) {

        Item item = new Item(produto, valorUnitario, quantidade);

        if (item != null) {
            items.add(item);
            }
    }

    public void adicionarItem(Item item) {
        if (item != null) {
            items.add(item);
        }

    }   

    public boolean removerItem(Produto produto) {

        Item item = new Item(produto );

            items.remove(item);

        return true;
        /*if(items.stream().anyMatch()
                        if (produto != null) {          
            this.items.remove(produto); 
        */
    }

   public boolean removerItem(int posicaoItem) {


            return true;
            }


    public BigDecimal getValorTotal() {

        items.forEach(item -> this.valorTotal.add(item.getValorTotal()));

        return this.valorTotal;
    }

.

    
asked by anonymous 03.11.2018 / 19:27

1 answer

2

BigDecimal is an immutable class, such as String , for example. This means that you need to store the return of the invoked method on a variable, otherwise the computation performed is lost.

Here:

this.valorTotal.add(item.getValorTotal())

You do the sum, but do not throw the return to the variable valorTotal , then the sum is lost and valorTotal continues with the previous value, ie zero.

Change your code in iteration to:

for(BigDecimal item: items) {
   valorTotal = valorTotal.add(item.getValorTotal());
}

Lambda functions can only operate with constant variables, ie you can not change a variable inside a lambda function that has been declared and initialized outside of it, so the use of a traditional foreach . >     

03.11.2018 / 20:45