Lesson · Collections Framework
Map: beyond HashMap
13 min readMap
HashMap is one implementation of a bigger idea. The Map family (LinkedHashMap, TreeMap, EnumMap) and the compound operations (merge, computeIfAbsent) are what turn maps from storage into algorithms.
The family
Every Map promises the same contract: put, get, remove, containsKey, size: keys map to values, one value per key. The implementations differ only in ordering and cost, and they mirror the Set flavours exactly: HashMap is unordered O(1); LinkedHashMap threads a list through entries; TreeMap keeps keys sorted in a red-black tree, O(log n), and adds the NavigableMap surface: floorKey, ceilingKey, firstKey, subMap.
Beyond the big three: EnumMap is an array indexed by ordinal, brutally fast when the keys are an enum, and IdentityHashMap compares keys by == rather than equals for the rare identity-keyed case. ConcurrentHashMap, the multi-threaded workhorse, gets its own treatment in the concurrent collections lesson.
Every map is also a set factory
The reverse direction of the Set trick. A Map does not extend Collection, and it does not need to: it hands out live views, and two of them are sets.
config.entrySet().removeIf(e -> e.getValue().isBlank());
keySet()returns aSet<K>of the keys, and removing from it removes the mapping.entrySet()returns aSet<Map.Entry<K, V>>: the map as a set of key-value pairs. This is what for-each over a map iterates.values()is aCollection<V>, deliberately not a Set: two keys may share one value.- Views, not copies:
keySet()reflects every laterputandremove, andentrySet().removeIf(...)edits the map itself, which is the cleanest way to delete while iterating.
One structure, many faces. The map is the storage; the views are windows onto it. The Set lesson runs the same idea in reverse, with the map hiding inside the set.
Views board · one map, four windows
change the map, watch every viewThe map itself
Log
map.put("java", 1) · put("jvm", 2) · put("gc", 3)
Views, not copies: each lane is a window onto the same storage, so keySet and entrySet can even delete through it. The Set lesson runs the same trick in reverse.
The compound operations are the good part
putIfAbsent, getOrDefault, compute, computeIfPresent, computeIfAbsent and merge exist so that check-then-act becomes a single method call: one lookup instead of two, and atomic on concurrent maps.
merge is the counting idiom: map.merge(word, 1, Integer::sum) inserts 1 or adds to the existing count. computeIfAbsent is the memoisation idiom: map.computeIfAbsent(key, k -> expensiveLookup(k)) builds the value only on the first ask. These two patterns cover most real map code you will ever read.
LinkedHashMap's party trick
The constructor flag accessOrder changes what 'order' means: pass true and iteration follows least-recently-accessed first: every get() moves the entry to the end.
That plus one overridden method, removeEldestEntry, is a complete LRU cache: evict the eldest whenever the map outgrows its bound. Five lines of code, built into the JDK, and a favourite interview exhibit.
Edges that bite
put returns the previous value: null when it was new, which is why exists-checking with a non-null-valuing map usually wants containsKey instead.
HashMap tolerates null keys and null values; TreeMap refuses null keys because it must compare them. Map.of and Map.copyOf are immutable and reject null outright.
Modifying a map while for-eaching it throws ConcurrentModificationException. Prefer entrySet().removeIf(condition), or collect the doomed keys and remove them after the loop. And one more, seen weekly in reviews: computeIfAbsent's mapping function must not modify the map it is computing for; that is mutation during an in-progress structural change, with all the undefined fun that implies.
computeIfAbsent's function must not touch the map
Calling map.put / map.compute inside the mapping function of computeIfAbsent mutates the map mid-operation: in a HashMap that can throw ConcurrentModificationException or corrupt the bucket in progress. Compute the value from its key only; if it genuinely depends on other entries, take a copy of what you need before the call.
Interview angles
How do you count occurrences idiomatically?+
map.merge(key, 1, Integer::sum): one lookup, works for first and later occurrences alike. The verbose get-then-put-then-null-check version is what merge exists to delete.
computeIfAbsent vs getOrDefault: what's the difference?+
getOrDefault reads and defaults but never writes. computeIfAbsent returns the existing value or creates, stores and returns a new one, and on a ConcurrentHashMap the whole thing is atomic, so two threads can't both 'create'.
LinkedHashMap has two ordering modes: name them and a use for the second.+
Insertion order (default) and access order (accessOrder=true). Access order plus removeEldestEntry gives an LRU cache; iteration order then tells you what was used least recently.
HashMap vs TreeMap vs ConcurrentHashMap: one line each.+
HashMap: fastest, unordered, single-threaded, allows one null key. TreeMap: sorted keys and range queries at O(log n), no null key. ConcurrentHashMap: thread-safe by design, the default answer for shared maps.