0

I am trying to compare and update an item in a ArrayList<HashMap<String,String>>named cart. I am doing the following:

            cart_list.put("quantity", "" +5);   //cart_list is HashMap<String,String>
            cart_list.put("item_id", "" + 1);
            cart.add(cart_list);

            cart_list.put("quantity", "" +6);   //cart_list is HashMap<String,String>
            cart_list.put("item_id", "" + 1);
            cart_list.put("prefernces", "no salt");  
            cart.add(cart_list);

I want to update the 'preferencesfromno salttoxtra salt`. Can anyone tell me step by step how to do it?

6
  • Ann, little bit unclear? What you want to do exactly dear? Commented Aug 14, 2014 at 9:10
  • ou'd get the proper HashMap from the array list then put the new value in it. Like this: cart_list.get(1).put("preferences", "xtra sale"); The trick is that you'd need to figure out which item in the list to update, and you don't give enough info for us to figure that part out. Commented Aug 14, 2014 at 9:10
  • @pratik I am trying to update the preferences value in the ArrayList. But the problem is that they have the same item_id i.e 1. So i am not able to figure out how to proceed. Commented Aug 14, 2014 at 9:21
  • @Ann that means instead of "no salt" you want new value everytime? Commented Aug 14, 2014 at 9:22
  • Initially I add the above mentioned values to a arraylist<hashmap>. Now I want to update that same arraylist<hashmap> with the preferences changed to xtra salt. Commented Aug 14, 2014 at 9:24

1 Answer 1

1

You need to get your appropriate HashMap from your list

Map<String,String> map = cart.get(n);

where n is the index of the HashMap in your list (remember the first list will be index 0), so if you wanted the first HashMap in your list, you'd do

Map<String,String> map = cart.get(0);

Then, you can simply overwrite the previous value, since a key (e.g. prefernces) can only map to one value, this will overwrite the previous value.

map.put("prefernces", "xtra salt");

Note that your keys have to exactly match, and in your code you've used "prefernces" and then in your comments you use "preferences", which are different spellings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.