LinkedHashMap & TreeMap
LinkedHashMap insertion/access order, TreeMap sorted navigation, ceiling/floor APIs
- Implement a simple LRU Cache using LinkedHashMap
- Use TreeMap for range queries with floorKey / ceilingKey
- Choose the right Map implementation for a given problem
Table of Contents
- LinkedHashMap — Overview
- LinkedHashMap Node Structure
- How Insertion Order is Maintained
- Access Order & LRU Cache
- LinkedHashMap Thread Safety
- LinkedHashMap Time Complexity
- TreeMap — Overview
- TreeMap Internal Structure
- TreeMap Hierarchy — SortedMap & NavigableMap
- SortedMap Methods
- NavigableMap Methods
- TreeMap Code Examples
- HashMap vs LinkedHashMap vs TreeMap
- Common Mistakes
- Interview Notes
- Practice Questions
- Summary Revision Bullets
1. LinkedHashMap Overview
Why It Exists
HashMap provides no guarantee on iteration order. LinkedHashMap solves this by maintaining a doubly-linked list over all entries — giving predictable, ordered iteration — while keeping the same O(1) average performance as HashMap.
Two Ordering Modes
| Mode | Description | How to Enable |
|---|---|---|
| Insertion Order (default) | Entries returned in the order they were put() | new LinkedHashMap<>() |
| Access Order | Least-recently-used → most-recently-used | new LinkedHashMap<>(capacity, loadFactor, true) |
Position in Hierarchy
LinkedHashMap extends HashMap. It is not a separate implementation — it builds on top of HashMap's hash table and adds a doubly-linked list layer.2. LinkedHashMap Node Structure
HashMap Node vs LinkedHashMap Node
1// HashMap.Node — 4 fields2static class Node<K,V> {3 final int hash;4 final K key;5 V value;6 Node<K,V> next; // next in same bucket (collision chain)7}8
9// LinkedHashMap.Entry — 6 fields (extends HashMap.Node)10static class Entry<K,V> extends HashMap.Node<K,V> {11 Entry<K,V> before; // previous node in ordering chain12 Entry<K,V> after; // next node in ordering chain13}Every LinkedHashMap node participates in two independent chains simultaneously:
| Chain | Pointer used | Purpose |
|---|---|---|
| Bucket/collision chain | .next | Fast O(1) lookup (same as HashMap) |
| Ordering chain | .before / .after | Ordered iteration |
Memory Layout
1LinkedHashMap {1="A", 21="B", 23="C"}2
3Hash Table (buckets):4[0] → Node{key=1, value="A", next=→Node_21}5 ↓.next6 Node{key=21, value="B", next=null}7[1] → Node{key=23, value="C", next=null}8
9Doubly-Linked List (before/after):10head → [key=1] ↔ [key=21] ↔ [key=23] ← tail11 (inserted first) (inserted last)3. How Insertion Order is Maintained
Step-by-Step: Inserting `{1="A", 21="B", 23="C", 141="D", 25="E"}` into a size-3 map
| Insert | Hash Table Change | Doubly-Linked List State |
|---|---|---|
put(1,"A") | [0] → {key=1} | head → [1] → tail |
put(21,"B") | [0] → {key=1}→{key=21} (collision) | head → [1]↔[21] → tail |
put(23,"C") | [1] → {key=23} | head → [1]↔[21]↔[23] → tail |
put(141,"D") | [2] → {key=141} | head → [1]↔[21]↔[23]↔[141] → tail |
put(25,"E") | [1] → {key=23}→{key=25} (collision) | head → [1]↔[21]↔[23]↔[141]↔[25] → tail |
How Iteration Works
Iteration follows the doubly-linked list via .after from head to tail — not the hash table array. This guarantees insertion-order output regardless of bucket distribution.
1// Conceptually:2Entry current = head;3while (current != null) {4 yield current;5 current = current.after;6}Code Example
1import java.util.*;2
3public class LinkedHashMapDemo {4 public static void main(String[] args) {5
6 // HashMap — no order guarantee7 Map<Integer, String> hashMap = new HashMap<>();8 hashMap.put(1, "A"); hashMap.put(21, "B"); hashMap.put(23, "C");9 hashMap.put(141, "D"); hashMap.put(25, "E");10 System.out.println("HashMap: " + hashMap);11 // e.g. {1=A, 141=D, 21=B, 23=C, 25=E} ← unpredictable12
13 // LinkedHashMap — insertion order guaranteed14 Map<Integer, String> linkedMap = new LinkedHashMap<>();15 linkedMap.put(1, "A"); linkedMap.put(21, "B"); linkedMap.put(23, "C");16 linkedMap.put(141, "D"); linkedMap.put(25, "E");17 System.out.println("LinkedHashMap: " + linkedMap);18 // {1=A, 21=B, 23=C, 141=D, 25=E} ← always insertion order19 }20}Output
1HashMap: {1=A, 141=D, 21=B, 23=C, 25=E}2LinkedHashMap: {1=A, 21=B, 23=C, 141=D, 25=E}4. Access Order & LRU Cache
What is Access Order?
In access-order mode, every get() or put() call moves the accessed node to the tail. The result:
- Head = Least Recently Used (LRU)
- Tail = Most Recently Used (MRU)
How it Works Internally
When get(key) is called and accessOrder=true, LinkedHashMap calls afterNodeAccess() which:
- Unlinks the node from its current position in the doubly-linked list.
- Appends it to the tail.
- Updates neighbors'
before/afterpointers.
Access Order Code Example
1Map<Integer, String> map = new LinkedHashMap<>(16, 0.75f, true); // accessOrder=true2map.put(1, "A"); map.put(21, "B"); map.put(23, "C");3map.put(141, "D"); map.put(25, "E");4
5System.out.println("Before: " + map);6// {1=A, 21=B, 23=C, 141=D, 25=E}7
8map.get(23); // access key 23 → moves to tail9System.out.println("After get(23): " + map);10// {1=A, 21=B, 141=D, 25=E, 23=C}11
12map.get(1); // access key 1 → moves to tail13System.out.println("After get(1): " + map);14// {21=B, 141=D, 25=E, 23=C, 1=A}LRU Cache Implementation
1import java.util.*;2
3public class LRUCache<K, V> extends LinkedHashMap<K, V> {4 private final int capacity;5
6 public LRUCache(int capacity) {7 super(capacity, 0.75f, true); // accessOrder = true8 this.capacity = capacity;9 }10
11 // Called after every put() — evicts LRU (head) when over capacity12 @Override13 protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {14 return size() > capacity;15 }16
17 public static void main(String[] args) {18 LRUCache<Integer, String> cache = new LRUCache<>(3);19 cache.put(1, "A"); cache.put(2, "B"); cache.put(3, "C");20 System.out.println(cache); // {1=A, 2=B, 3=C}21
22 cache.get(1); // key 1 → tail; head = key 2 (LRU)23 cache.put(4, "D"); // capacity exceeded → evict head (key 2)24 System.out.println(cache); // {3=C, 1=A, 4=D}25
26 cache.put(5, "E"); // evict head (key 3)27 System.out.println(cache); // {1=A, 4=D, 5=E}28 }29}Output
1{1=A, 2=B, 3=C}2{3=C, 1=A, 4=D}3{1=A, 4=D, 5=E}get and put. It is a very popular interview question — knowing LinkedHashMap can implement it in ~10 lines is highly valued.5. LinkedHashMap Thread Safety
LinkedHashMap is not thread-safe. There is no concurrent or synchronized variant built into the JDK. Use Collections.synchronizedMap() to wrap it:
1Map<Integer, String> safeMap =2 Collections.synchronizedMap(new LinkedHashMap<>());Internally, synchronizedMap wraps every method call in a synchronized(mutex) block — coarse-grained locking, similar to HashTable.
synchronizedMap, iteration must be manually synchronized:
``java
synchronized (safeMap) {
for (Map.Entry e : safeMap.entrySet()) { ... }
}
``6. LinkedHashMap Time Complexity
| Operation | Average | Worst Case |
|---|---|---|
put / get / remove | O(1) | O(log N) |
| Iteration | O(N) | O(N) |
Identical to HashMap. The extra before/after pointer updates are always O(1) (constant pointer reassignment). Iteration over LinkedHashMap is actually faster than HashMap in sparse maps — it traverses only live entries via the linked list, not the entire backing array.
7. TreeMap Overview
What is TreeMap?
TreeMap stores entries in sorted key order using a Red-Black Tree (self-balancing BST) internally. Unlike HashMap/LinkedHashMap which use hashing, TreeMap uses key comparison for all operations.
Key Characteristics
| Property | Detail |
|---|---|
| Ordering | Natural ascending OR custom Comparator |
| Null keys | ❌ Not allowed (comparison on null → NPE) |
| Null values | ✅ Allowed |
| Thread-safe | ❌ No |
| Internal structure | Red-Black Tree |
| All operations | O(log N) |
8. TreeMap Internal Structure
Red-Black Tree
A Red-Black Tree is a self-balancing BST that maintains these properties to guarantee O(log N) height:
- Every node is RED or BLACK.
- Root is always BLACK.
- No two consecutive RED nodes.
- Every root-to-null path has the same number of BLACK nodes.
This guarantees the tree height ≤ 2 log(N+1), ensuring O(log N) for all operations.
BST Property
1Left child key < Parent key < Right child keyIn-order traversal always yields keys in ascending sorted order.
TreeMap Node Structure
1// Inside TreeMap (simplified):2static final class Entry<K,V> implements Map.Entry<K,V> {3 K key;4 V value;5 Entry<K,V> left; // smaller keys6 Entry<K,V> right; // larger keys7 Entry<K,V> parent;8 boolean color; // RED or BLACK9}No hash field — TreeMap doesn't use hashing. No next field — no collision chaining needed.
Inserting {4, 1, 5} Visual
1Insert 4: Insert 1: Insert 5:2 4 4 43 / / \4 1 1 5New keys placed by BST rules (left if smaller, right if larger), then Red-Black rebalancing applied.
9. TreeMap Hierarchy SortedMap & NavigableMap
TreeMap sits at the bottom of a three-level hierarchy, implementing all methods from Map, SortedMap, and NavigableMap.
10. SortedMap Methods
Setup for all examples:
1// Sorted order: 5, 11, 13, 212TreeMap<Integer, String> map = new TreeMap<>();3map.put(5, "E"); map.put(11, "K"); map.put(13, "M"); map.put(21, "U");| Method | Returns | Example Result |
|---|---|---|
firstKey() | Smallest key | 5 |
lastKey() | Largest key | 21 |
headMap(toKey) | Keys < toKey (exclusive) | headMap(13) → {5=E, 11=K} |
tailMap(fromKey) | Keys ≥ fromKey (inclusive) | tailMap(13) → {13=M, 21=U} |
subMap(from, to) | Keys from inclusive, to exclusive | subMap(11,21) → {11=K, 13=M} |
headMap is exclusive on the upper bound. tailMap is inclusive on the lower bound. This asymmetry trips up many developers.11. NavigableMap Methods
Setup for all examples:
1// Sorted order: 1, 21, 23, 25, 1412TreeMap<Integer, String> map = new TreeMap<>();3map.put(1,"A"); map.put(21,"B"); map.put(23,"C"); map.put(25,"D"); map.put(141,"E");The Four Navigation Directions
| Direction | Meaning | On key 23 | On key 24 (absent) |
|---|---|---|---|
lowerKey(k) | Strictly < k | 21 | 23 |
floorKey(k) | ≤ k | 23 | 23 |
ceilingKey(k) | ≥ k | 23 | 25 |
higherKey(k) | Strictly > k | 25 | 25 |
Each direction also has an *Entry variant that returns Map.Entry (both key and value) instead of just the key.
1map.lowerEntry(23); // Entry{21=B}2map.lowerKey(23); // 213map.floorEntry(23); // Entry{23=C} ← equal exists4map.floorEntry(24); // Entry{23=C} ← 24 absent, return greatest ≤ 245map.ceilingEntry(24); // Entry{25=D} ← 24 absent, return smallest ≥ 246map.higherEntry(23); // Entry{25=D}7map.lowerKey(1); // null ← no key < 18map.higherKey(141); // null ← no key > 141Boundary & Poll Methods
1map.firstEntry(); // Entry{1=A} — read only, doesn't remove2map.lastEntry(); // Entry{141=E} — read only, doesn't remove3map.pollFirstEntry(); // Entry{1=A} — removes AND returns smallest4map.pollLastEntry(); // Entry{141=E} — removes AND returns largest5// map is now {21=B, 23=C, 25=D}Descending Operations
1map.descendingMap(); // {141=E, 25=D, 23=C, 21=B, 1=A} — reverse-order view2map.descendingKeySet(); // [141, 25, 23, 21, 1] — keys only, descendingNavigableMap's Enhanced headMap / tailMap (with inclusivity control)
1map.headMap(23, true); // {1=A, 21=B, 23=C} ← 23 INCLUDED2map.headMap(23, false); // {1=A, 21=B} ← 23 excluded (same as SortedMap.headMap)3map.tailMap(23, true); // {23=C, 25=D, 141=E} ← 23 INCLUDED (same as SortedMap.tailMap)4map.tailMap(23, false); // {25=D, 141=E} ← 23 excludedheadMap(key, inclusive) / tailMap(key, inclusive) when you need explicit control over whether the boundary key is included. This is cleaner than trying to compute key+1 or key-1.12. TreeMap Code Examples
Example 1 Default Ascending Order
1import java.util.*;2
3public class TreeMapAscending {4 public static void main(String[] args) {5 TreeMap<Integer, String> map = new TreeMap<>();6 map.put(13, "M"); map.put(5, "E"); map.put(21, "U"); map.put(11, "K");7
8 System.out.println(map); // {5=E, 11=K, 13=M, 21=U}9
10 System.out.println("firstKey: " + map.firstKey()); // 511 System.out.println("lastKey: " + map.lastKey()); // 2112 System.out.println("headMap(<13): " + map.headMap(13)); // {5=E, 11=K}13 System.out.println("tailMap(>=13): " + map.tailMap(13)); // {13=M, 21=U}14 }15}Example 2 Custom Descending Order via Comparator
1import java.util.*;2
3public class TreeMapDescending {4 public static void main(String[] args) {5 TreeMap<Integer, String> map = new TreeMap<>((k1, k2) -> k2 - k1); // descending6 map.put(13, "M"); map.put(5, "E"); map.put(21, "U"); map.put(11, "K");7
8 System.out.println(map); // {21=U, 13=M, 11=K, 5=E}9 }10}Example 3 Full Navigation Demo
1import java.util.*;2
3public class TreeMapNavigation {4 public static void main(String[] args) {5 TreeMap<Integer, String> map = new TreeMap<>();6 map.put(1,"A"); map.put(21,"B"); map.put(23,"C"); map.put(25,"D"); map.put(141,"E");7 // Sorted: {1, 21, 23, 25, 141}8
9 System.out.println("lowerKey(23): " + map.lowerKey(23)); // 2110 System.out.println("floorKey(24): " + map.floorKey(24)); // 2311 System.out.println("ceilingKey(24): " + map.ceilingKey(24)); // 2512 System.out.println("higherKey(23): " + map.higherKey(23)); // 2513
14 System.out.println("pollFirstEntry: " + map.pollFirstEntry()); // 1=A (removed)15 System.out.println("pollLastEntry: " + map.pollLastEntry()); // 141=E (removed)16 System.out.println("After polls: " + map); // {21=B, 23=C, 25=D}17
18 System.out.println("descendingMap: " + map.descendingMap()); // {25=D, 23=C, 21=B}19
20 System.out.println("headMap(23,true): " + map.headMap(23, true)); // {21=B, 23=C}21 System.out.println("tailMap(23,false): " + map.tailMap(23, false)); // {25=D}22 }23}Output
1lowerKey(23): 212floorKey(24): 233ceilingKey(24): 254higherKey(23): 255pollFirstEntry: 1=A6pollLastEntry: 141=E7After polls: {21=B, 23=C, 25=D}8descendingMap: {25=D, 23=C, 21=B}9headMap(23,true): {21=B, 23=C}10tailMap(23,false): {25=D}13. HashMap vs LinkedHashMap vs TreeMap
Full Comparison Table
| Feature | HashMap | LinkedHashMap | TreeMap |
|---|---|---|---|
| Internal structure | Hash table | Hash table + doubly-linked list | Red-Black Tree |
| Key ordering | None | Insertion order OR access order | Sorted (natural/Comparator) |
| Null keys | ✅ 1 allowed | ✅ 1 allowed | ❌ Not allowed |
| Null values | ✅ | ✅ | ✅ |
| Thread-safe | ❌ | ❌ | ❌ |
put/get complexity | O(1) avg | O(1) avg | O(log N) |
| Iteration | O(N+capacity) | O(N) | O(N) |
| Extra memory/node | Low | +2 pointers | +3 pointers + color |
| Range queries | ❌ | ❌ | ✅ (SortedMap/NavigableMap) |
Decision Guide
14. Common Mistakes
Mistake 1 Null Key in TreeMap
1TreeMap<String, Integer> map = new TreeMap<>();2map.put(null, 1); // ❌ NullPointerException — cannot compare nullFix: Use HashMap if null keys are needed.
Mistake 2 Confusing headMap / tailMap inclusivity
1// Map: {5, 10, 15, 20}2map.headMap(15); // {5, 10} — 15 EXCLUDED3map.tailMap(15); // {15, 20} — 15 INCLUDEDFix: Use NavigableMap's overloaded versions: headMap(15, true) to include 15.
Mistake 3 Confusing lower/floor/ceiling/higher
1// Map: {5, 10, 15}2map.floorKey(10); // 10 (≤ 10, equal counts)3map.lowerKey(10); // 5 (strictly < 10)4map.ceilingKey(10); // 10 (≥ 10, equal counts)5map.higherKey(10); // 15 (strictly > 10)Mistake 4 Expecting HashMap/LinkedHashMap to Support Range Queries
1HashMap<Integer, String> map = new HashMap<>();2map.headMap(10); // ❌ Compile error — HashMap has no headMap methodFix: Use TreeMap for range queries.
Mistake 5 Using TreeMap When Ordering Not Needed
TreeMap is O(log N) for every operation. If you don't need sorted order, always use HashMap for O(1) average performance.
15. Interview Notes
Q1: How does LinkedHashMap maintain insertion order?
Answer: By adding before and after pointers to every node, forming a doubly-linked list in insertion sequence. Iteration traverses this list from head to tail via .after — not the hash table array — guaranteeing insertion-order output.
Q2: How would you implement an LRU cache using LinkedHashMap?
Answer: Create a LinkedHashMap with accessOrder=true and override removeEldestEntry() to return true when size() > capacity. Every get() moves the accessed node to the tail (MRU). When capacity is exceeded, the head (LRU) is automatically evicted. Both get and put are O(1).
Q3: What is the internal data structure of TreeMap?
Answer: Red-Black Tree — a self-balancing BST. All operations are O(log N). In-order traversal always gives keys in ascending sorted order.
Q4: Can TreeMap have null keys? Why?
Answer: No. TreeMap must compare keys to maintain sorted order. Calling compareTo() or a Comparator on null throws NullPointerException.
Q5: What is the difference between `lowerKey`, `floorKey`, `ceilingKey`, `higherKey`?
Answer: lower = strictly less than (<). floor = less than or equal (≤). ceiling = greater than or equal (≥). higher = strictly greater than (>). All return null if no such key exists.
Q6: Difference between `firstEntry()` and `pollFirstEntry()`?
Answer: firstEntry() reads the smallest-key entry without modifying the map. pollFirstEntry() removes it from the map AND returns it. Returns null if map is empty.
Q7: How to make LinkedHashMap thread-safe?
Answer: Collections.synchronizedMap(new LinkedHashMap<>()). Must also manually synchronize during iteration. For high concurrency, there is no standard concurrent LinkedHashMap; consider ConcurrentHashMap (loses order) or a custom implementation.
Q8: Why is TreeMap O(log N) while HashMap is O(1)?
Answer: HashMap hashes the key to a bucket index — direct array access is O(1). TreeMap must traverse a tree from root to leaf to find the right position, which takes O(log N) where N is the number of entries.
Tricky Points
LinkedHashMapis a subclass ofHashMap— it inherits all HashMap behavior (load factor, treeify, rehashing).- In access-order mode, calling
get()modifies the map's structure. Iterating while callingget()is unsafe without synchronization. TreeMap.headMap(),tailMap(),subMap()return live views — changes in the view reflect in the original map and vice versa.descendingMap()returns a reverse-order view — no copying, O(1) to create.TreeMapwithComparator.reverseOrder()stores in descending order natively.descendingMap()is a view of an existing map.Collections.synchronizedMap()uses coarse-grained locking — one lock for the entire map.ConcurrentHashMapuses segment-level locking and is much faster under high concurrency.
16. Practice Questions
Easy
- Create a
LinkedHashMapwith 5 entries. Print them and verify insertion order. - What constructor argument enables access-order mode in
LinkedHashMap? - What does
TreeMap.firstKey()return? - Is
headMap(toKey)inclusive or exclusive? What abouttailMap(fromKey)? - Can you store a null key in a
TreeMap?
Medium
- Trace the state of a
LinkedHashMap(accessOrder=true, capacity=3) as you insert keys 1,2,3, thenget(1), then insert key 4. - What extra fields does
LinkedHashMap.Entryhave compared toHashMap.Node? Why are they needed? - Using a
TreeMap, find all entries with keys strictly between 10 and 50. - What is the difference between
lowerKey(23)andfloorKey(23)when the map contains key 23? - Implement a method that uses
TreeMapto return the k-th smallest key.
Hard
- Implement a bounded LRU cache with O(1)
getandputusingLinkedHashMap. TreeMap.headMap()returns a live view. Write code that modifies the view and shows the change reflected in the original map.- Compare memory per entry for
HashMap,LinkedHashMap, andTreeMap. Which uses the most and why? - When would
ConcurrentSkipListMapbe preferred over a synchronizedTreeMap? - Write a word-frequency counter using
HashMap, then print words sorted by frequency descending using aTreeMapwith a custom comparator.
17. Summary Revision Bullets
LinkedHashMap
- Extends
HashMap— same hash table, same O(1) average performance. - Adds
before/afterpointers to every node → doubly-linked list over all entries. - Two modes: insertion order (default) and access order (
accessOrder=true). - Access order:
get()/put()moves node to tail → head = LRU, tail = MRU. - Basis for LRU cache — override
removeEldestEntry()to auto-evict. - Not thread-safe. Wrap with
Collections.synchronizedMap(). - Iteration follows linked list (O(N)) — faster than HashMap in sparse maps.
TreeMap
- Red-Black Tree internally — self-balancing BST.
- All keys always in sorted order. No null keys.
- All operations O(log N) — slower than HashMap/LinkedHashMap average.
- Not thread-safe. Use
ConcurrentSkipListMapfor concurrent sorted-map. - Implements
SortedMap→firstKey,lastKey,headMap,tailMap,subMap. - Implements
NavigableMap→lower,floor,ceiling,higher,poll,descending.
Quick Reference NavigableMap
| Method | Condition | Returns null when |
|---|---|---|
lowerKey(k) | Greatest key < k | No key less than k |
floorKey(k) | Greatest key ≤ k | No key ≤ k |
ceilingKey(k) | Smallest key ≥ k | No key ≥ k |
higherKey(k) | Smallest key > k | No key greater than k |
headMap(k) | Keys < k | — |
tailMap(k) | Keys ≥ k | — |
headMap(k, true) | Keys ≤ k | — |
tailMap(k, false) | Keys > k | — |
When to Use Which Map
| Use Case | Best Choice |
|---|---|
| Fast lookup, order irrelevant | HashMap |
| Preserve insertion order | LinkedHashMap |
| LRU cache | LinkedHashMap (accessOrder=true) |
| Sorted keys, range queries | TreeMap |
| Thread-safe, fast | ConcurrentHashMap |
| Thread-safe, sorted | ConcurrentSkipListMap |
End of Chapter — LinkedHashMap & TreeMap
Mastery check
How well can you recall this?
Finished this lesson?