Add specific data from an arrayList [closed]

-3

In the following arrayList:

Nombre: Producto1, CodProducto: 1, Precio: 10.0

Nombre: Producto2, CodProducto: 2, Precio: 20.0

Nombre: Producto3, CodProducto: 3, Precio: 30.0

How can I add the price elements?
I want to get the total sum of the prices.

    
asked by InThaHouse 19.04.2018 в 20:24
source

3 answers

1

I assume that the ArrayList that you indicate is of some Object that owns those fields that you mention. One way to do it would be:

double precioTotal = 0;

for(Objeto objeto : arrayListObjeto) {
    precioTotal += objeto.getPrecio();
}

System.out.println(precioTotal);

Or from Java 8 using streams and lambdas:

double precioTotal= arrayListObjeto.stream()
      .mapToDouble(o -> o.getPrecio())
      .sum();
System.out.println(precioTotal);
    
answered by 19.04.2018 в 20:38
0

int result = products [0] .price + products [1] .price;

you just have to choose the products you need and add their prices: P

    
answered by 19.04.2018 в 20:35
0

Here I show you an example based on the data you already have:

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
         Data dato1 = new Data("Producto1",1,10.0);
         Data dato2 = new Data("Producto2",2,20.0);
         Data dato3 = new Data("Producto3",3,30.0);
       ArrayList<Data> arrayList = new ArrayList<Data>();
       arrayList.add(dato1);
       arrayList.add(dato2);
       arrayList.add(dato3);

        Double total = 0.00;
        for (Data data : arrayList) {
           total += data.Precio; 
        }
        System.out.println(total);
     }
}

class Data {
    String Nombre;
    Integer CodProducto;
    Double Precio;

    Data(String nombre,Integer codProducto,Double precio){  
        this.Nombre = nombre;  
        this.CodProducto = codProducto;  
        this.Precio = precio;  
    }  
}

Here's the example

    
answered by 19.04.2018 в 20:43