I was trying to use ideas given here to adjust a nested hashmap but my solution does not work: How to update a value, given a key in a java hashmap?. My nested hashmap is shoppingLists
. It contains an outer hashmap of shopping list listID
as key and a hashmap of items as values. The items hashmap contains itemName
as key and the amount of the item as the value. The adjustItemAmount
attempts to adjust the amount of an item by a given amount x
.
HashMap<String, HashMap<String, Integer>> shoppingLists = new HashMap<>();
public void adjustItemAmount(String itemName, int x, String listID) {
int current_amount = shoppingLists.get(listID).get(itemName);
HashMap<String, Integer> items = shoppingLists.get(listID);
HashMap updatedItems = items.put(itemName, items.get(itemName) + x);
shoppingLists.put(listID, updatedItems);
}
The line HashMap updatedItems = items.put(itemName,items.get(itemName)+x);
states that Java expects a hashmap but gets an integer. I do not see how that is the case.