'HashMap - Adding a value to a specific item [duplicate]

public void addItem(String itemName,int numItemAdd) {

    HashMap <String,Integer> items = new HashMap<String,Integer>();
            
    int totalval;
    
    totalval =+ numItemAdd;
    
    items.put(itemName,totalval);
    
}

I am new to HashMaps. I am wanting to add the integers to the specific itemName. For example, addItem("socks",100); addItem("socks",200). Whenever I do this, instead of getting 300 I only get 200. I know that put() replaces the last value used, but I do not know how to add the numbers so that I can get 300 instead of having the last value used.



Solution 1:[1]

You can try this, it also manages the case when socks don't exist:

    private HashMap <String,Integer> items = new HashMap<String,Integer>();

    public static void main(String[] args) {
        Test test = new Test();
        test.addItem("socks", 100);
        test.addItem("socks", 200);
    }

    public void addItem(String itemName,int numItemAdd) {
        items.put(itemName,items.get(itemName) != null ? (items.get(itemName) + numItemAdd) : numItemAdd);
        System.out.println("Socks value:" + items.get(itemName));
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 happy songs