Lesson 15 of 23
In progress
HashMap and keyed lookup
Map keys to values, use getOrDefault and compute, and understand why mutable keys and missing equals break a map.
A list finds items by position. A map finds them by key, which is what most lookups actually need: a user by id, a count by word, a price by product code.
What you will learn
- Put, get, and update entries.
- Use
getOrDefault,computeandmergeinstead of null checks. - Avoid the two classic map bugs.
The basics
import java.util.HashMap;
import java.util.Map;
public class Counts {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 40);
stock.put("book", 12);
stock.put("lamp", 0);
System.out.println(stock.get("book")); // 12
System.out.println(stock.get("desk")); // null
System.out.println(stock.containsKey("pen")); // true
System.out.println(stock.size()); // 3
stock.remove("lamp");
System.out.println(stock.keySet()); // [pen, book]
}
}
put returns the previous value for that key, or null. get returns null for a missing key, which is why getOrDefault exists.
Iteration order is not defined for HashMap. Use LinkedHashMap to keep insertion order or TreeMap to sort by key.
Counting idiom
String text = "a b a c b a";
Map<String, Integer> counts = new HashMap<>();
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts); // {a=3, b=2, c=1}
merge(key, 1, Integer::sum) inserts 1 when the key is absent and combines with the existing value otherwise. It replaces the four-line containsKey dance and cannot be got wrong.
The older idiom:
counts.put(word, counts.getOrDefault(word, 0) + 1);
That also works and is worth recognising in existing code. It reads well and avoids an explicit null check.
Defaults and computation
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 40);
int pens = stock.getOrDefault("pen", 0); // 40
int desks = stock.getOrDefault("desk", 0); // 0
stock.computeIfAbsent("book", k -> 0);
stock.computeIfPresent("pen", (k, v) -> v - 1);
stock.compute("lamp", (k, v) -> v == null ? 5 : v + 1);
computeIfAbsent is the standard way to build a map of lists:
Map<String, java.util.List<String>> byCity = new HashMap<>();
byCity.computeIfAbsent("Pune", k -> new java.util.ArrayList<>()).add("Ana");
Without it, you need a null check plus an allocation, which is exactly the code that gets written wrong under time pressure.
compute receives the current value or null, and its return value replaces the entry; returning null removes the key. That makes it possible to update and delete in one expression, which is powerful and worth using sparingly.
The equals and hashCode contract
A map finds a key by hash, then by equals. Two rules follow:
- If you override
equals, overridehashCode. - Do not mutate a key after putting it in the map.
record Point(int x, int y) { }
Map<Point, String> labels = new HashMap<>();
labels.put(new Point(1, 2), "origin-ish");
System.out.println(labels.get(new Point(1, 2))); // origin-ish
A record generates a correct equals and hashCode, so this works. A hand-written class with only equals can store a value and then fail to find it, because the hash changed the bucket it looks in.
Mutable keys fail the same way: if a key’s field changes after insertion, the map looks in a different bucket and reports the key as missing, even though it is still there. Use immutable types as keys — strings, numbers, records.
Null keys and values
HashMap allows one null key and any number of null values; TreeMap and ConcurrentHashMap do not. A null value is indistinguishable from a missing key via get, so containsKey is the only way to tell them apart.
The practical advice: avoid null values in maps. Use Optional or a sentinel, or simply omit the entry. A map where get returning null means "absent" is easier to reason about than one where it might mean "present and null".
Views and copies
Map<String, Integer> stock = new HashMap<>(Map.of("pen", 40, "book", 12));
for (Map.Entry<String, Integer> entry : stock.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
Map<String, Integer> copy = Map.copyOf(stock);
keySet, values and entrySet are views: they reflect changes to the map, and removing through them removes from the map. Map.copyOf makes an immutable copy, which is the safe thing to return from a method.
Map.of takes up to ten pairs and is immutable. For more, use a builder or a static initialiser.
When a map is the wrong choice
If the keys are a small fixed set, an enum with fields is clearer and type-safe. If you need ordering by key, say so with TreeMap rather than sorting afterwards. If the values are all the same and you only need membership, a Set is the right structure.
Using a mutable object as a key and changing it after insertion. The entry becomes unreachable: get looks in the bucket for the new hash, and the entry sits in the old one.
Count the frequency of each word in a sentence, then print the words that appear more than once in alphabetical order.
Show solution
import java.util.Map; import java.util.TreeMap; public class Words { public static void main(String[] args) { String text = "the quick brown fox jumps over the lazy dog the end"; Map<String, Integer> counts = new TreeMap<>(); for (String word : text.split("\s+")) { if (!word.isBlank()) { counts.merge(word.toLowerCase(), 1, Integer::sum); } } counts.forEach((word, count) -> { if (count > 1) { System.out.println(word + ": " + count); } }); } } TreeMap sorts by key, so the output is alphabetical without a separate sort. merge handles the first occurrence and the repeats in one line, and lowercasing before counting keeps "The" and "the" together.
Recap
mergeandcomputeIfAbsentreplace the null-check patterns and are harder to get wrong.- Keys must be immutable with a correct
equalsandhashCode; records give you that. HashMaphas no order; chooseLinkedHashMaporTreeMapwhen order matters.
Next, exceptions: what to catch, what to let propagate, and how to keep messages useful.
How fast is a HashMap lookup?
Should I use Map.of for constants?
Progress is saved in this browser only. No account, no email.