Collection of an Object making calculations with Bigdecimal

Asked

Viewed 158 times

-1

I have the attribute valorTotal this value must be represented by the sum of all items in the Item class that are in the list items, I am trying to make the sum of all the items in the list that are Bigdecimal, but when I execute the value is 0, IE, is not calculating, I would like to 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;
    }

.

  • Your question is a bit confused, try to improve it and point out exactly where the problem is giving.

  • I’ve made changes now, I’m sorry!

1 answer

1

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

Here:

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

you make the sum, but do not play the return for the variable valorTotal, then the sum is lost and valorTotal continues with the previous value, that is, zero.

Change your code in iteration to:

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

lambda functions can only operate with constant variables, that is, you cannot, within a lambda function, change a variable that has been declared and initialized outside it, so the use of a foreach traditional.

  • 1

    Thank you Statelessdev, I had tried this way, but for some reason I did not add up either, but I succeeded in making the method this way: Bigdecimal valueTotal = items.stream(). map(Item::getValorTotal) . reduce(Bigdecimal.ZERO, Bigdecimal::add);

Browser other questions tagged

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