Seo-Jun Koh Seo-Jun Koh - 5 months ago 11
Java Question

Searching an arrayList for an object and then adding value to that same object more than once

I just started working with arrayLists - basically what I need to figure out is how to search my arrayList and if that same object is found to add a new total value to it versus just swapping it out.

ie.

arrayList = (hats, $45)


and I have a new value to add to hats (ie. $10 dollars) - so the ultimate new total for hats = $55

...and if hats are not in the list already to add it.

Any help is appreciated !

Answer

Filling an ArrayList with String and Integer will not be possible unless you use a nested ArraysList or Map. But you can create a simple class for your ProductName and the Price and create An ArraysList which contains for the Name and price.

public class Products {

private String product;
private int price;

public Products(String product, int price){
    this.product = product;
    this.price = price;
}
public String getProduct(){
    return this.product;
}
public int getPrice(){
    return this.price;
}

@Override
public String toString(){
    return this.product +" "+ this.price;
}



public static void main(String[] args) throws ParseException {

    ArrayList<Products> list = new ArrayList<>();
    list.add(new Products("Hat",45));
    list.add(new Products("Socks",10));

    for (Products gd: list){
        if (gd.getProduct().equals("Hat")){
            int index = list.indexOf(gd);
            list.set(index,new Products(gd.getProduct(),gd.getPrice+10));
        }else {
            // if productName not found
            System.out.println("sorry products not available");
            break;
        }
    }

    System.out.println(list);

}

}

output:

[Hat 55, Socks 10]

But if you don't want all this class and want to still use the ArrayList for the job then you can do this with ArrayList containing both name and price

ArrayList<String> list = new ArrayList<>();
    list.add("Hat,45");
    list.add("Socks,15");

    for (String ss:list){
        String[] spl = ss.split(",");
        if (spl[0].equals("Hat")){
            int index = list.indexOf(ss);
            int value = Integer.parseInt(spl[1])  +10;
            list.set(index,(spl[0]+","+value));
        }
    }


    System.out.println(list);

output:

[Hat,55, Socks,15]