Start learning free

LESSON 129 OF 285 · DICTIONARIES - CHALLENGES

Restock in Java: Updating a HashMap Value

Practice Read the full explanation

A shop keeps its stock in inventory, a HashMap from item names to how many of each item it has. A delivery brings amount more of item. Add amount to the count of item and return the updated dictionary.

Only the count of item changes: every other entry stays as it is. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas", amount = 3
Output: {"apples": 5, "bananas": 5, "cherries": 10}
Explanation: "bananas" had a count of 2, and 2 + 3 = 5. The apples and the cherries keep their counts.

Example 2:

Input: inventory = {"milk": 0}, item = "milk", amount = 12
Output: {"milk": 12}
Explanation: A count of 0 means the milk was sold out. The delivery brings it to 0 + 12 = 12.

Example 3:

Input: inventory = {"pens": 7, "paper": 3}, item = "pens", amount = 1
Output: {"pens": 8, "paper": 3}
Explanation: One more pen: 7 + 1 = 8.

 

Constraints:

  • item is always a key of inventory.
  • amount is at least 1.
  • Every count is 0 or more.
  • Item names are single lowercase words, and they are all different.
STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · DICTIONARIES - CHALLENGES

    Restock in Java, explained

    Problem overview

    A shop keeps its stock in inventory, a HashMap<String, Integer> from item names to counts. The method restock receives an item that is already a key and an amount of at least 1. It adds amount to that item's count and returns the updated map. Every other entry stays as it was.

    With {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas" and amount = 3, the bananas go from 2 to 5, and the apples and cherries keep their counts. With {"milk": 0} and an amount of 12, the result is {"milk": 12}.

    Approach: read the old count, write back the new one

    A map has no "add to this value" operation. The update takes two moves: read the current count with get, add amount, and store the sum under the same key with put. When put receives a key that is already in the map, it replaces that key's value and leaves the other entries alone.

    Step by step

    1. Put the item back with its new count. The value is inventory.get(item) + amount, the old count plus the delivery.
    2. Return inventory. The map was changed in place, so it already holds every entry with only one count different.

    The solution in Java

    class Solution {
        public HashMap<String, Integer> restock(HashMap<String, Integer> inventory, String item, int amount) {
            inventory.put(item, inventory.get(item) + amount);
            return inventory;
        }
    }
    

    Java details behind the two lines:

    • Boxing. The map stores Integer objects, but inventory.get(item) + amount is ordinary int arithmetic. Java unboxes the stored value, adds, and boxes the sum again when put stores it.
    • get can return null. For a missing key, unboxing that null throws a NullPointerException. For example, restock on an empty map with the item "tea" fails that way. The lesson promises the item is a key, so the plain get is safe here. getOrDefault(item, 0) would also handle new items.
    • The map is changed in place. The method returns the same object it was given, not a copy.
    • Order doesn't matter. A HashMap doesn't promise any entry order, which is why the lesson ignores it. Printing a HashMap can list the entries in a surprising order.

    Other ways to write the update

    The two-step get and put is the clearest form. Java's maps also offer merge, which does the read, the addition and the write in one call: inventory.merge(item, amount, Integer::sum) turns {"bananas": 2} into {bananas=5} for an amount of 3. When the key is absent, merge simply stores the amount, so merge("kiwi", 4, Integer::sum) on that map adds kiwi=4.

    The version with getOrDefault handles new items too: inventory.put(item, inventory.getOrDefault(item, 0) + amount) adds ink=5 to a map that has no ink. This lesson only needs the plain get, because the item is always present.

    Edge cases and common mistakes

    • Sold-out items. A count of 0 works like any other count: 0 + 12 is 12.
    • Putting only amount. inventory.put(item, amount) replaces the count instead of adding to it. The milk example would pass by accident, and the bananas would end at 3 instead of 5.
    • Forgetting the return. The map is updated, but the method must still return it.
    • Touching other keys. Only item changes. There's no loop over the map.

    Testing

    • {"apples": 5, "bananas": 2, "cherries": 10}, "bananas", 3 gives {apples=5, bananas=5, cherries=10}.
    • {"milk": 0}, "milk", 12 gives {milk=12}.
    • {"pens": 7, "paper": 3}, "pens", 1 gives {paper=3, pens=8}.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free