- Prerequisites
- 4.1 Collection Architecture
- Covers
- HashMap · LinkedHashMap · TreeMap · EnumMap · WeakHashMap · IdentityHashMap
- Related
- 5.1 HashMap Internals · 5.3 Tree-Based Collections · 5.4 Equality & Hashing · 7.3 Specialized Collections · B2V4 ConcurrentHashMap
On this page
1Concept / Definition
A Map associates unique keys with values. The JDK provides six general and special-purpose implementations in java.util, each defined by how it finds keys (hashing, comparison, ordinal index, identity), what iteration order it guarantees, and how it treats key lifetime. Choosing among them is a matter of matching these properties to the use case.

| Implementation | Key lookup by | Order | get/put | Null keys | Typical use |
|---|---|---|---|---|---|
| HashMap | hashCode + equals | None | O(1) avg | One | Default map |
| LinkedHashMap | hashCode + equals | Insertion or access | O(1) avg | One | Ordered output, LRU caches |
| TreeMap | compareTo / Comparator | Sorted | O(log n) | No (natural order) | Ranges, nearest keys |
| EnumMap | Enum ordinal | Declaration | O(1) | No | Enum-keyed data |
| WeakHashMap | hashCode + equals | None | O(1) avg | One | Metadata tied to key lifetime |
| IdentityHashMap | == and identityHashCode | None | O(1) avg | One | Object-graph algorithms |
2Why It Exists
Key–value lookup is the most common data-access pattern in software: caches, indexes, lookup tables, grouping, counting. No single structure is best for all of it: sorted range queries need a tree, enum keys allow an array, some keys must not be kept alive, and some algorithms need identity rather than equality. Hence six maps sharing one interface.
3Core Concepts
HashMap
The default map: an array of buckets indexed by the key's hash, with collisions chained in linked lists that turn into balanced trees when long (5.1). Average O(1) get and put, one null key and any number of null values, no ordering guarantee, not thread-safe. Its correctness depends entirely on keys having consistent, immutable equals and hashCode (5.4).
LinkedHashMap
A HashMap whose entries are also linked in a doubly linked list. By default iteration follows insertion order; constructed with accessOrder = true, it follows access order, moving an entry to the end whenever it is read or written. Overriding removeEldestEntry then turns it into a simple LRU cache. It implements SequencedMap (Java 21), including putFirst, putLast and reversed.

TreeMap
A red-black tree ordered by the keys' natural ordering or a Comparator (5.3). Operations are O(log n). As a NavigableMap it offers firstKey, floorKey, ceilingEntry, headMap, tailMap, subMap and descendingMap, all as views. Key equality is decided by the comparator. It is the map for time series, price ladders, version ranges and anything queried by "nearest" or "between".
EnumMap
A map with keys of one enum type, stored in an array indexed by ordinal(). It is extremely compact and fast, iterates in enum declaration order, and rejects null keys. Use it wherever keys are enum constants — counts per status, handlers per event type, configuration per environment.
WeakHashMap
A hash map whose keys are held through weak references: once a key object is no longer strongly reachable elsewhere, the garbage collector may clear it, and the entry is removed the next time the map is accessed. Values are held strongly, so a value that references its own key keeps the entry alive forever — the classic WeakHashMap leak. Useful for associating metadata with objects owned by someone else; not a general-purpose cache, because eviction depends on GC timing rather than size or age.

IdentityHashMap
A map that compares keys with == and hashes them with System.identityHashCode, deliberately violating the general Map contract. It uses open addressing (linear probing) in a single array. It is intended for algorithms that must track object identity — graph traversal, deep copying, serialisation, proxies — where two equal but distinct objects must be treated separately.

4How It Works Internally
HashMap, LinkedHashMap and WeakHashMap use bucket arrays with chaining; IdentityHashMap uses linear probing in one array of alternating keys and values; TreeMap uses red-black tree nodes; EnumMap uses a plain array indexed by ordinal. WeakHashMap registers its keys' weak references with a ReferenceQueue and purges cleared entries on subsequent operations (expungeStaleEntries). Chapter 5 covers HashMap and TreeMap in depth.

The lookup rule in Figure 5 explains each map's cost and its notion of "the same key". EnumMap needs no hashing at all: it keeps a vals array indexed by ordinal(), a parallel keys array shared by all maps of that enum, and a size. IdentityHashMap stores keys and values side by side in one Object[] and probes the next pair of slots on a collision, so it allocates no entry objects. LinkedHashMap threads a before/after list through ordinary hash entries; in access order a get moves the entry to the tail, and after each insertion removeEldestEntry is asked whether to drop the head.
One consequence is easy to miss: in an access-ordered LinkedHashMap, get is a structural change, because it reorders the list. Iterating over the key set and calling get inside the loop throws ConcurrentModificationException; iterate over entrySet() instead.
5APIs / Features / Syntax

Map<String, Integer> counts = new HashMap<>();
for (String word : words) counts.merge(word, 1, Integer::sum); // counting
Map<CustomerId, List<Order>> byCustomer = new HashMap<>();
for (Order o : orders) {
// multimap
byCustomer.computeIfAbsent(o.customerId(), k -> new ArrayList<>()).add(o);
}
int stock = inventory.getOrDefault(sku, 0);
inventory.putIfAbsent(sku, 0);
counts.replaceAll((k, v) -> v * 2);
counts.entrySet().removeIf(e -> e.getValue() == 0);
Map<String, Integer> presized = HashMap.newHashMap(10_000); // Java 19+6Practical Examples
Example 1 — Bounded LRU cache
public final class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
public LruCache(int capacity) {
super(16, 0.75f, true); // accessOrder = true
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity; // evict least-recently used
}
}
// Not thread-safe: wrap with Collections.synchronizedMap or use a cache library
// (Caffeine) for concurrent production use.Used with a capacity of 3, the cache evicts by recency of use, not by insertion:
import t44.LruCache;
public class LruDemo {
public static void main(String[] args) {
LruCache<String, String> cache = new LruCache<>(3);
cache.put("p1", "pen");
cache.put("p2", "ink");
cache.put("p3", "pad");
cache.get("p1"); // p1 becomes most recently used
cache.put("p4", "nib"); // evicts p2, least recently used
System.out.println(cache.keySet());
cache.getOrDefault("p3", "?"); // a read also counts as access
cache.put("p5", "cap"); // evicts p1
System.out.println(cache.keySet()
+ " eldest=" + cache.firstEntry().getKey());
}
}[p3, p1, p4]
[p4, p3, p5] eldest=p4get("p1") moved p1 behind p3, so p2 became the eldest and was evicted by the fourth put. getOrDefault counts as an access too, and firstEntry() (Java 21) shows the next victim. Reads reorder the map, which is why even a read-only workload needs a lock around this cache once threads share it.
Example 2 — Mini program: an access-log report from four maps
Problem. From a day's access log, report the busiest pages, the hits per status class, the hits per hour with a range query, the next busy hour after noon, and the hour each page was first seen. Each question gets the map that answers it directly.
import java.util.*;
public class AccessLogReport {
enum Status { OK, CLIENT_ERROR, SERVER_ERROR }
record Hit(int hour, String page, int code) {
Status status() {
return code >= 500 ? Status.SERVER_ERROR
: code >= 400 ? Status.CLIENT_ERROR : Status.OK;
}
}
public static void main(String[] args) {
List<Hit> log = List.of(
new Hit(9, "/cart", 200), new Hit(9, "/home", 200),
new Hit(10, "/cart", 500), new Hit(10, "/pay", 200),
new Hit(11, "/cart", 200), new Hit(11, "/home", 404),
new Hit(13, "/pay", 503), new Hit(13, "/cart", 200));
Map<String, Integer> perPage = new HashMap<>(); // by key
Map<Status, Integer> perStatus = new EnumMap<>(Status.class);
NavigableMap<Integer, Integer> perHour = new TreeMap<>(); // sorted
Map<String, Integer> firstSeen = new LinkedHashMap<>(); // arrival
for (Hit h : log) {
perPage.merge(h.page(), 1, Integer::sum);
perStatus.merge(h.status(), 1, Integer::sum);
perHour.merge(h.hour(), 1, Integer::sum);
firstSeen.putIfAbsent(h.page(), h.hour());
}
var top = new ArrayList<>(perPage.entrySet());
top.sort(Map.Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()));
System.out.println("top pages " + top);
System.out.println("by status " + perStatus);
System.out.println("by hour " + perHour);
System.out.println("10:00-12:59 " + perHour.subMap(10, true, 12, true));
System.out.println("next from 12 " + perHour.ceilingEntry(12));
System.out.println("first seen at " + firstSeen);
}
}top pages [/cart=4, /home=2, /pay=2]
by status {OK=5, CLIENT_ERROR=1, SERVER_ERROR=2}
by hour {9=2, 10=2, 11=2, 13=2}
10:00-12:59 {10=2, 11=2}
next from 12 13=2
first seen at {/cart=9, /home=9, /pay=10}Why it behaves this way. merge(key, 1, Integer::sum) inserts 1 or adds to the existing count in one lookup. The HashMap has no useful order, so the top list sorts a copy of its entries by value, highest first, then by key to make ties stable. The EnumMap prints in declaration order and shows every class that occurred; the TreeMap sorts the hours, subMap(10, true, 12, true) is a view of the range, and ceilingEntry(12) finds the first hour at or after noon, 13. putIfAbsent into a LinkedHashMap records each page once, in the order it first appeared.
Example 3 — Nearest-key lookup with TreeMap
NavigableMap<LocalTime, BigDecimal> tariff = new TreeMap<>(Map.of(
LocalTime.of(0, 0), new BigDecimal("4.00"),
LocalTime.of(7, 0), new BigDecimal("8.50"),
LocalTime.of(22, 0), new BigDecimal("5.00")));
// 8.50
BigDecimal rateNow = tariff.floorEntry(LocalTime.of(13, 45)).getValue();
NavigableMap<LocalTime, BigDecimal> evening = tariff.tailMap(LocalTime.of(18, 0), true);Example 4 — EnumMap for per-status handling
enum Status { NEW, PAID, SHIPPED, CANCELLED }
Map<Status, Long> counts = orders.stream()
.collect(Collectors.groupingBy(Order::status,
() -> new EnumMap<>(Status.class), Collectors.counting()));
EnumMap<Status, OrderHandler> handlers = new EnumMap<>(Status.class);
handlers.put(Status.PAID, new ShipmentHandler());Example 5 — Metadata without leaks
// Associate computed metadata with objects we don't own, without keeping them alive
private final Map<ClassLoader, PluginMetadata> meta =
Collections.synchronizedMap(new WeakHashMap<>());
// Value must NOT reference the key strongly, or the entry is never cleared.Example 6 — IdentityHashMap: equal values, distinct objects
Problem. A graph walk must visit each node object once. The nodes are records, so two nodes with the same data are equal, and the graph has a cycle. A HashMap of visited nodes gives the wrong answer, or worse.
import java.util.*;
public class IdentityVsEquality {
record Node(String name, List<Node> links) { }
static int countReachable(Node start, Map<Node, Boolean> visited) {
if (visited.put(start, true) != null) return 0; // seen before
int n = 1;
for (Node next : start.links()) n += countReachable(next, visited);
return n;
}
public static void main(String[] args) {
String a = new String("SKU-1"), b = new String("SKU-1");
Map<String, Integer> byEquals = new HashMap<>();
Map<String, Integer> byIdentity = new IdentityHashMap<>();
for (String key : List.of(a, b)) {
byEquals.put(key, 1);
byIdentity.put(key, 1);
}
System.out.println("a.equals(b) " + a.equals(b) + ", a == b " + (a == b));
System.out.println("HashMap size " + byEquals.size()
+ ", IdentityHashMap size " + byIdentity.size());
// two nodes with equal values but distinct identities
List<Node> links = new ArrayList<>();
Node hub = new Node("hub", links);
Node left = new Node("bay", List.of(hub));
Node right = new Node("bay", List.of(hub));
links.addAll(List.of(left, right));
System.out.println("left.equals(right) " + left.equals(right));
System.out.println("reachable by identity "
+ countReachable(hub, new IdentityHashMap<>()));
try {
countReachable(hub, new HashMap<>()); // hashCode follows the cycle
} catch (StackOverflowError e) {
System.out.println("reachable by equals StackOverflowError");
}
}
}a.equals(b) true, a == b false
HashMap size 1, IdentityHashMap size 2
left.equals(right) true
reachable by identity 3
reachable by equals StackOverflowErrorWhy it behaves this way. The two strings are equal but not the same object, so a HashMap holds one entry and an IdentityHashMap two. For the graph, IdentityHashMap uses System.identityHashCode and ==, so it counts all three node objects even though left and right are equal. A HashMap must call the record's hashCode, which hashes the links list, which hashes the nodes in it, and around the cycle again until the stack overflows. Serialisers, deep-copy utilities and object-graph tools use identity maps for exactly this reason.
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Mutable keys (or keys whose hashCode changes) | Entries lost, memory leaks: contains and get miss the entry, which stays in the map for ever | Immutable keys; records whose fields cannot change after the put |
| HashMap shared between threads | Lost updates, corrupted structure, infinite loops in old JDKs, and a size() that is wrong | ConcurrentHashMap (B2V4) |
| WeakHashMap as a size-bounded cache | Evicts unpredictably, or never (strong value → key); neither size nor age bounds it | Caffeine or a bounded LinkedHashMap with explicit size and expiry |
| String keys in WeakHashMap | Interned/literal strings never collected: the key stays reachable, so the entry is never cleared | Use objects with real lifecycles as keys that live and die with the data, such as ClassLoader or Thread |
| TreeMap comparator inconsistent with equals | Keys merged unexpectedly: a put with "Asha" replaces the value of "asha" | Comparator consistent with equals, or normalise keys before the put |
| Counting with get + put | Verbose; racy if shared, and the get + put pair is two lookups | merge / compute (Example 2) |
| HashMap<Enum, V> | Wasted memory and time: an entry object and hashing per key where an array slot would do | EnumMap (Example 4) |
| Calling get while iterating the keys of an access-ordered LinkedHashMap | get reorders the entries, so the iterator throws ConcurrentModificationException | Iterate entrySet(), or use insertion order for that map |
| Relying on the iteration order of Map.of or HashMap | Map.of randomises its order per JVM run, HashMap's changes on resize; tests flake | LinkedHashMap or TreeMap when order matters |
8Performance & Production Considerations
- A HashMap entry costs about 32–48 bytes plus key and value objects; a million entries with boxed keys easily consume 80–100 MB.
- Pre-size large maps with
HashMap.newHashMap(n)to avoid repeated resizing (5.1). - TreeMap trades O(log n) operations for ordering; on large maps with only point lookups it is 3–10 times slower than HashMap.
- Caches built from LinkedHashMap need external synchronisation and offer no statistics or expiry; production caches usually use Caffeine (in-process) or a distributed cache (Book 7).
- Poor
hashCodeimplementations degrade HashMap to O(log n) or worse; hash-flooding attacks with crafted keys were a reason for treeification (5.1).
9Architecture & Design Considerations
Maps are at the heart of caching, indexing and aggregation designs. Architectural questions to ask: Is the map bounded? Who evicts, and on what policy — size, time, reference reachability? Is it shared across threads? Must it survive restarts or be consistent across instances, in which case an in-process map is the wrong tool? Is key equality a stable domain concept?

10Interview Questions & Answers
What is the difference between HashMap, LinkedHashMap and TreeMap?
HashMap: hashing, no order, O(1) average. LinkedHashMap: HashMap plus a linked list for insertion or access order. TreeMap: red-black tree sorted by key, O(log n), with navigation methods.
Can HashMap have null keys and values?
One null key (stored in bucket 0) and any number of null values. TreeMap with natural ordering rejects null keys; EnumMap rejects null keys.
How do you implement an LRU cache with the JDK?
Extend LinkedHashMap with accessOrder = true and override removeEldestEntry to return true when size exceeds the capacity. Add synchronisation for concurrent use, or use a library such as Caffeine in production.
When would you use EnumMap?
Whenever keys are constants of one enum: it is array-based, compact, very fast, and iterates in declaration order.
How does WeakHashMap decide when to remove entries?
Keys are held via weak references registered with a reference queue. When the GC clears a key because it is no longer strongly reachable, the entry is purged the next time the map is accessed.
What is IdentityHashMap used for?
Algorithms where object identity matters rather than equality — tracking visited nodes in graph traversal, deep copying, serialisation, and proxies. It compares keys with == and uses identity hash codes.
Why can a WeakHashMap still leak memory?
Values are strongly referenced. If a value refers to its own key directly or indirectly, the key stays strongly reachable through the map, so the entry is never cleared. Keys such as interned strings or class constants are never collected either.
Why is using a TreeMap with a comparator that ignores case risky for a map of user names?
Keys that differ only in case compare as equal, so a put with "Asha" overwrites "asha". That may be intended, but equals on the map may then disagree with other Map implementations, and lookups depend on the comparator rather than equals.
How would you design caching for a service that looks up product details from a slow API?
Use a bounded, expiring in-process cache (Caffeine) with size and TTL chosen from traffic data, metrics for hit rate and evictions, and refresh-ahead if staleness matters. If several instances must share results or survive restarts, add a distributed cache. A raw HashMap would grow unbounded and never expire.
When would you choose TreeMap over HashMap in a system design?
When operations need order: range queries (all events between t1 and t2), nearest matches (floor or ceiling tariff), sorted iteration, or first/last access. If only point lookups are needed, HashMap is faster and smaller.
Your platform has dozens of ad-hoc static HashMap caches across services. What would you do?
Inventory them and their risks (unbounded growth, thread safety, staleness), then provide a standard caching abstraction backed by Caffeine with mandatory size and TTL, metrics and naming. Migrate the highest-risk caches first, add static-analysis rules against new static mutable maps, and decide which data belongs in a shared distributed cache instead.
What does this program print?
import java.util.*;
public class MapQuiz {
public static void main(String[] args) {
Map<String, Integer> users = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
users.put("Asha", 1);
users.put("asha", 2);
System.out.println(users);
Map<String, Integer> stock = new HashMap<>(Map.of("pen", 1));
stock.merge("pen", -1, (old, d) -> old + d == 0 ? null : old + d);
stock.computeIfAbsent("ink", k -> null);
System.out.println(stock + " " + stock.containsKey("ink"));
}
}It prints {Asha=2} and then {} false. The case-insensitive TreeMap treats "asha" as the existing key "Asha": the value is replaced but the original key is kept. merge removes the entry when the remapping function returns null, so "pen" disappears when its count reaches 0, and computeIfAbsent stores nothing when the mapping function returns null.
A unit test that prints Map.of("a", 1, "b", 2) passes on one run and fails on the next. Why?
The immutable maps and sets returned by Map.of and Set.of deliberately randomise their iteration order with a per-JVM salt, so that nobody can come to depend on it. HashMap order is not promised either, but it only changes with the capacity or the hash codes, which hides the dependency until it breaks. Compare maps with equals, or use LinkedHashMap or TreeMap when the order is part of the expected result.
Why does iterating the keySet of an access-ordered LinkedHashMap and calling get for each key throw ConcurrentModificationException?
With accessOrder = true, get moves the entry it finds to the tail of the linked list, which changes the iteration order and increments modCount. The key set's iterator detects the change on its next next(). Iterating entrySet() and reading getValue() does not count as an access, so it is safe; so is an insertion-ordered map. The same reasoning explains why an LRU cache needs synchronisation even when every caller only reads.
For a product cache in a service with 2,000 requests per second, would you use a synchronised LinkedHashMap LRU or Caffeine?
The LinkedHashMap LRU is small and dependency-free, but every get must take the lock because it reorders the list, so all request threads serialise on one monitor, and it has no expiry, statistics or loading. Caffeine records accesses in buffers drained asynchronously, so reads scale across cores, and it adds size and time bounds, refresh, metrics and an admission policy that keeps the hit rate higher than plain LRU. At that load, and wherever data can go stale, Caffeine; the LinkedHashMap version is fine for a single-threaded tool or a very small, rarely read cache.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 15 questions, filtered by level and type.
Key Takeaways
- HashMap is the default; LinkedHashMap adds order and enables LRU; TreeMap adds sorting and navigation.
- EnumMap for enum keys; WeakHashMap for key-lifetime metadata; IdentityHashMap for identity semantics.
- Keys must be immutable with correct equals/hashCode (or a consistent comparator).
- In-process maps are unbounded, non-expiring caches unless you make them otherwise.