Java: Is it possible to compare String values in two arrays, and if they match, increment an int value in the first array?

user10745934 :

I'd like to build an arraylist by adding an array composed of String name, double price, int quantity representing different items. If an item is added which is identical to one that is already in the arraylist, it should increment quantity instead of being added.

My thought process was to check if the values for index 1 between 2 arrays match, and if they do, increment the value for index 3 in the first array. Is this something that's possible to do in Java? How would you compare a new array to arrays already in a list?

RPresle :

You should probably review your model and use an object.

Create a class containing your three attributes. Then a Map<String, YourObject>. Then when you want to add your Object just do a test before

if(map.containsKey(objectName)) {
    YourObject object = map.get(objectName);
    object.setQuantity(object.getQuantity() + 1);
}

EDIT After discussing with @Eugene

YourObject objectToAdd = ...
Map<String, YourObject> map = new HashMap<>();
...
YourObject objectInMap = map.get(objectName);
if(objectInMap != null) {
    // increase Quantity in objectInMap 
} else {
    //Object not existing in the map, never added
    //manage initial quantity here
    map.put(objectToAdd.getName(), objectToAdd)
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116623&siteId=1