How to access item in Arraylist

Asked

Viewed 105 times

2

I created a ArrayList for a purchasing system each object is a Item(product), which has the nome, quantidade and preço. However I am willing to make the sum of all prices of all objects that are added within this Array to make the total purchase.

Someone knows how to do this?

Test class:

public static void main(String[] args) {
    ArrayList<Item> c1 = new ArrayList<>();
    Scanner in = new Scanner(System.in);
    int opcao=0;

......

case 4:
   System.out.println("--------------");
   System.out.println("TOTAL DA LISTA");
   System.out.println("--------------");
   break;

Item class

public class Item {
public String nome;
public int quantidade;
public double preco;

public Item(){
    ler();
}

public void ler() {
    Scanner lc = new Scanner(System.in);
    System.out.println("Digite o produto que deseja inserir: ");
    this.nome = lc.nextLine();
    System.out.println("Digite a quantidade que deseja: ");
    this.quantidade = lc.nextInt();
    System.out.println("Digite o valor do produto: ");
    this.preco = lc.nextDouble();
}

3 answers

1

Just use a stream together with sum:

double soma = items.stream()
  .mapToDouble(item -> item.getQuantidade() * item.getPreco())
  .sum();

Remember to encapsulate the amount with private and create the getters for quantidade and preco.


mapToDouble

Returns a Doublestream consisting of the Results of Applying the Given Function to the Elements of this stream.

In free translation:

Returns a Doublestream consisting of the results of the function application given to the elements of this stream.


sum

Returns the sum of Elements in this stream. Summation is a special case of a reduction.

In free translation:

Returns the sum of the elements in this stream. The sum is a special case of reduction.

0

Come on:

First, create some getters for your code:

public int getQuantidade(){
return this.quantidade;
}

public double getPreco{
return this.preco;
}

With that, we can return the price and quantity of a particular item on the list, right? Well, I advise you to create a loop, with a variable to accumulate the sum, like this:

double sum = 0;
for(int i = 0; i < c1.size() ; i++){
    sum += c1.get(i).getPreco()*c1.get(i).getQuantidade();
}

Explanation: Like c1 is the name of your list, we’re going through it with a for loop. We have to method c1.get(i) returns an object of type Item, which is in position i of the list. With this, we pass through all the elements of the list, and carry out the sum.

0

Your approach is putting an object of the domain model (i.e., an object that represents something of the problem that your application deals with, in the case of product sales) a behavior of reading keyboard data. It would be like putting code that saves this data in the database or code that displays this data on the screen. Although they are related, this is not where they should be, because they are not behaviors of what this object represents. In a larger project this would be potentially problematic for maintenance.

Besides, your Item confuses the concepts of Produto (due to the field nome) and ItemDePedido (due to the fields quantidade and preco).

I suggest you model a class Pedido which has a list of objects in a class ItemDePedido, this with fields quantidade and preco (beyond is clear of a field produto which is not the name but a reference to an object of the class Produto, this yes can have a field nome -- although, see the end of the text).

Do this class ItemDePedido have a method getSubtotal() which returns the multiplication of these first two fields quantidade and preco.

That method getSubtotal() is a specialized operation (liability) that objects ItemDePedido are able to perform on their internal state (i.e., their fields). This is more object-oriented.

And finally in class Pedido create a method getTotal() who traverses the list by invoking each itemDePedido.getSubtotal() and using to calculate the total order.

Another appropriate class responsibility Pedido would be adicionar(ItemDePedido item).

It is thus clear that a request item must be built (i.e., have its fields initialized) by passing the values to these fields in the constructor already previously read from a keyboard reading done externally to that class.

By the way, this class Produto (that represents an instance of product in stock) should not be confused with DescricaoDeProduto, which represents the generic description of the product in the store, which has no quantity in stock and remains existing even if the products come out of stock. Maybe then a product should have a product description and it should have a name.

To go deeper, see "Using UML and Standards" (3rd edition), by Craig Larman.

P.S.: All of this can be ignored and done in ways that people have put in other responses. If it is object-oriented and brings the benefits that this approach proposes, that is another story (although in part what was proposed in them by being applied here). Remembering that in the simple case it may not seem so effective, but OO was made to deal with complexity. The code may become more complex in this case but at least it is not based on arbitrary modeling or "taken from the hat".

Browser other questions tagged

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