Map operations and null contracts
What you will learn
A map associates a unique key with a value, like a product code with its stock count. Unlike a list, a map retrieves by key rather than position. Updating an existing key replaces its value; different keys may share the same value.
- Choose a map based on key and iteration-order requirements.
- Distinguish a missing key from a key mapped to null.
- Update counts and groups and use backed views safely.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Read and distinguish missing and null keys
import java.util.*;public class Main {
public static void main(String[] args) { Map<String, Integer> stock = new HashMap<>(); stock.put("pen", 4); stock.put("book", null); System.out.println(stock.put("pen", 7)); System.out.println(stock.get("pen")); System.out.println(stock.getOrDefault("ruler", 0)); System.out.println(stock.getOrDefault("book", 0)); System.out.println(stock.containsKey("book")); System.out.println(stock.containsKey("ruler")); }}Expected output:
470nulltruefalseReplacing pen returns the old count; get reads the new count. Book is present with a null value, so the default is not substituted.
Rules and mental model
Declare Map<String, Integer> stock = new HashMap<>(); when you need key-based lookup without ordering requirements. A Map is not a Collection, although keySet(), values() and entrySet() expose collection views. HashMap accepts a null key and null values, and does not promise encounter order. Its usual lookup and insertion cost is constant with well-distributed hashes; collisions occur when keys share a hash and are resolved using equality. Do not mutate a key in a way that changes its equality while it is stored. LinkedHashMap normally preserves insertion order; replacing an existing mapping does not move it. Its optional access-order mode is useful for tracking recent use. TreeMap compares keys and keeps them sorted, with logarithmic lookup and updates. A comparator that returns zero for unequal keys can collapse distinct keys. Natural-order TreeMap rejects null keys; a suitable comparator may permit them. EnumMap requires keys from one enum and iterates in declaration order; null values are allowed but null keys are not. Map.of and Map.copyOf prohibit null keys and values and return unmodifiable maps; Map.of also rejects duplicate keys. Map equality compares mappings, not encounter order.
get(k) returns null both for an absent key and for a stored null where supported. containsKey(k) distinguishes these cases. getOrDefault(k,d) uses d only when the key is absent. putIfAbsent and computeIfAbsent also treat a null mapping as needing a value. compute recalculates using the current value (null if absent); merge inserts a supplied non-null value for missing/null mappings, otherwise combines values. A null result from compute or merge removes a mapping; computeIfAbsent returning null leaves no new mapping. These methods do not establish atomicity for ordinary maps. The lambda (oldValue, added) -> oldValue + added is a small callback: the map supplies two values and the expression returns their sum. Lambdas are taught fully in the next chapter.
Views are backed by the map. Where supported, removing through an iterator or calling an entry’s setValue during entry iteration changes the original map. Avoid structural changes through the map while using an ordinary iterator. Fail-fast detection is not a correctness guarantee.
Count words with merge and predictable order
import java.util.*;public class Main {
public static void main(String[] args) { Map<String, Integer> counts = new TreeMap<>(); for (String word : List.of("pear", "apple", "pear", "plum")) { counts.merge(word, 1, (oldValue, added) -> oldValue + added); } for (Map.Entry<String, Integer> entry : counts.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } }}Expected output:
apple: 1pear: 2plum: 1The first pear is inserted, the second is added to its count. TreeMap orders the printed keys alphabetically.
Group inventory and remove a group
import java.util.*;public class Main {
public static void main(String[] args) { Map<String, List<String>> groups = new LinkedHashMap<>(); groups.computeIfAbsent("desk", key -> new ArrayList<>()).add("pen"); groups.computeIfAbsent("shelf", key -> new ArrayList<>()).add("book"); groups.computeIfAbsent("desk", key -> new ArrayList<>()).add("pad"); System.out.println(groups); Iterator<String> keys = groups.keySet().iterator(); while (keys.hasNext()) { if (keys.next().equals("shelf")) keys.remove(); } System.out.println(groups); }}Expected output:
{desk=[pen, pad], shelf=[book]}{desk=[pen, pad]}The callback creates a list only when needed. Removing the key via its iterator removes the entire group. The insertion order is retained.
Compare enum order and access order
import java.util.*;public class Main { enum Zone { NORTH, SOUTH } public static void main(String[] args) { Map<Zone, Integer> counts = new EnumMap<>(Zone.class); counts.put(Zone.SOUTH, 2); counts.put(Zone.NORTH, 5); System.out.println(counts); Map<String, Integer> recent = new LinkedHashMap<>(16, 0.75f, true); recent.put("A", 1); recent.put("B", 2); recent.get("A"); System.out.println(recent.keySet()); }}Expected output:
{NORTH=5, SOUTH=2}[B, A]The enum declaration fixes key order. Access-order LinkedHashMap moves a read key to the recent end. This is not a bounded cache by itself.
Common mistakes
Do not use get(k) == null as a universal missing-key test. Also avoid assuming merge is thread-safe or that a HashMap prints in insertion order. Use the actual implementation’s contract.
Practice
Count occurrences of ["red", "blue", "red", "green", "blue"] using a LinkedHashMap and merge. Remove green using the key view. Print the map and report whether green is present.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Map operations and null contracts — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
A HashMap stores "A" -> null. What does getOrDefault("A", 9) return?
Which map keeps keys sorted by their natural order by default?
What happens when merge combines values and its callback returns null?
Which operation distinguishes an absent key from a key mapped to null?
A keySet iterator removes a key from a mutable LinkedHashMap. What happens?