HashMap: keys to values
Half of programming is looking things up by name: the price for a product code, the user for a session token, the count for a word. Scanning a list for a match gets slower as data grows; a map answers by key in the same tiny time whether it holds ten entries or ten million, which is why some form of it sits inside almost every cache, index, and config system you will ever touch. A HashMap<K, V> is Java's dictionary: it stores key → value pairs and looks them up in constant time, like Python's dict.
import java.util.HashMap; HashMap<String, Integer> stock = new HashMap<>(); stock.put("apple", 3); // insert or overwrite stock.get("apple") // 3, or null if missing stock.getOrDefault("kiwi", 0) // 0 instead of null stock.containsKey("apple") // true stock.remove("apple"); stock.size();
Two differences from Python worth flagging: a missing key returns null rather than raising an error (prefer getOrDefault to dodge null), and a HashMap has no promised order when you loop over it.
Code exercise · java
Run this inventory demo. The second put for apple overwrites the first, and getOrDefault saves us from null for missing keys.
Quiz
stock.get("pear") is called and "pear" was never put in the map. What happens?
Looping over a map
A map is not a sequence, so looping takes one extra decision: do you want the keys, the values, or both? Each view has a method:
for (String key : stock.keySet()) { ... } // keys only for (int count : stock.values()) { ... } // values only for (Map.Entry<String, Integer> e : stock.entrySet()) { System.out.println(e.getKey() + ": " + e.getValue()); // both }
A Map.Entry<K, V> is one key-value pair; entrySet() hands you all of them, and needs import java.util.Map;. Prefer entrySet when you use both halves — looping keySet and calling get(key) inside does a second lookup per pass for nothing.
Code exercise · java
Run this. Note the printed order: banana, apple, kiwi — not the insertion order. A HashMap arranges entries by hash bucket, which is what "no promised order" means in practice. Then the values() loop totals the stock.
Code exercise · java
Your turn. Count how often each letter appears in the word banana. Loop over its characters with charAt, update counts using getOrDefault, then print the counts for a, b, and n in that order (format `a: 3`).