Maps: HashMap & TreeMap
Key-value storage, iteration, getOrDefault, merge, computeIfAbsent, TreeMap and LinkedHashMap.
A map stores key → value pairs, and finds a value by its key in an instant. Phone books, product catalogues keyed by SKU, word counts, caches, configuration settings and JSON objects are all maps. Map is arguably the most useful data structure in everyday Java.
HashMap basics#
Key rules:
- Keys are unique; values can repeat. Putting an existing key overwrites its value.
getreturnsnullfor a missing key. PrefergetOrDefaultorcontainsKeywhen absence is possible.HashMapoperations are O(1) on average, and it has no guaranteed order.- One
nullkey and any number ofnullvalues are allowed in aHashMap(but avoid them; they makegetambiguous).
Iterating over a map#
Because this is a TreeMap, every view (entrySet, keySet, values) comes out sorted by key. You will compare the three main map types shortly.
Tip: iterate over
entrySet()when you need both key and value. Looping overkeySet()and callingget(key)each time does a second lookup per key.
Counting and grouping: merge and computeIfAbsent#
Two methods make the most common map tasks one-liners:
merge(key, value, fn): if the key is absent, storevalue; otherwise storefn(oldValue, value).computeIfAbsent(key, k -> create): return the existing value, or create, store and return a new one. It is perfect for "map of lists".
Other handy methods:
HashMap vs LinkedHashMap vs TreeMap#
Use HashMap by default, LinkedHashMap when order of insertion matters (e.g. JSON output, LRU caches), and TreeMap when you need sorted keys or range queries. For enum keys, use EnumMap.
TreeMap navigation#
floorEntry turns "find the band this value falls into" into a single O(log n) call.
Immutable maps#
These are unmodifiable, reject null keys and values, and have unspecified iteration order.
How HashMap works (in brief)#
- The key's
hashCode()picks a bucket in an internal array. - Inside the bucket,
equals()finds the exact key. - When the map gets about 75% full (the load factor), the array doubles and entries are redistributed.
- Buckets with many colliding keys turn into small balanced trees (Java 8+), so worst-case lookups stay O(log n).
Therefore keys must have consistent equals and hashCode, and must not change while in the map. Strings, wrappers, enums and records make excellent keys.
A practical example: an inventory#
Common mistakes#
map.get(k) + 1on a missing key: aNullPointerExceptionfrom unboxingnull. UsemergeorgetOrDefault.- Relying on
HashMaporder. - Using mutable objects as keys and changing them after insertion.
- Modifying a map while iterating over it (other than through
iterator.remove()orentrySet().removeIf), which throwsConcurrentModificationException. - Sharing a plain
HashMapbetween threads. UseConcurrentHashMap(concurrency lessons).
What's next#
Sorted sets and maps need to know how to order elements. Next we look closely at Comparable vs Comparator, the two ways to define order in Java.
Check your understanding
Quick quiz
1.What does
map.put("a", 2)return if the map already contains"a"=1?2.Which is the most concise correct way to count word occurrences in a
Map<String, Integer> counts?3.You need a map whose keys are always iterated in sorted order. Which do you choose?
Finished reading?
Mark this lesson complete to track your progress.