LinkedHashMap in Java

LinkedHashMap extends HashMap with a doubly-linked list that preserves insertion or access order, making it ideal for LRU cache implementations.

LinkedHashMap<K, V> extends HashMap and maintains a doubly-linked list running through all its entries. The linked list records the order of entries in either insertion order (the default) or access order (when the accessOrder flag is set to true in the constructor). This makes LinkedHashMap the natural choice when you need HashMap performance with predictable iteration order, and it is the standard building block for a simple LRU cache in Java.

How LinkedHashMap Works Internally

LinkedHashMap inherits all hash-table mechanics from HashMap (buckets, treeification, resizing). On top of that, each entry has two additional pointers — before and after — that form a doubly-linked list across all entries in the order they were inserted (or accessed). The iterator follows this list rather than the bucket array, which gives O(n) ordered iteration regardless of the table's capacity.

Operation Average Worst case
put O(1) O(log n)
get O(1) O(log n)
remove O(1) O(log n)
Iteration O(n) O(n)

Two ordering modes:

Mode Constructor Iteration reflects
Insertion-order (default) new LinkedHashMap<>() Order keys were first added
Access-order new LinkedHashMap<>(capacity, 0.75f, true) Most recently accessed key is last

In access-order mode, get, put, and replace all move the accessed entry to the tail of the list.

Examples

Insertion-order iteration

import java.util.LinkedHashMap;
import java.util.Map;

public class InsertionOrder {
    public static void main(String[] args) {
        Map<String, Integer> steps = new LinkedHashMap<>();
        steps.put("connect", 1);
        steps.put("authenticate", 2);
        steps.put("query", 3);
        steps.put("disconnect", 4);

        // Iteration always reflects insertion order
        steps.forEach((k, v) -> System.out.println(v + ". " + k));
        // 1. connect
        // 2. authenticate
        // 3. query
        // 4. disconnect
    }
}

LRU cache using access-order and removeEldestEntry

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int maxSize;

    public LRUCache(int maxSize) {
        // access-order = true: moves accessed entries to the tail
        super(maxSize, 0.75f, true);
        this.maxSize = maxSize;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        // Remove the least-recently-used entry (head of list) when over capacity
        return size() > maxSize;
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(3);
        cache.put(1, "a");
        cache.put(2, "b");
        cache.put(3, "c");
        cache.get(1);       // access key 1 — moves it to tail
        cache.put(4, "d");  // evicts LRU entry (key 2)

        System.out.println(cache.containsKey(2)); // false — evicted
        System.out.println(cache.keySet());       // [3, 1, 4]
    }
}

Common Mistakes

  1. Using insertion-order mode and expecting access-order behaviour. In the default insertion-order mode, calling get does not affect the iteration order. If you need LRU semantics, you must construct with accessOrder = true.

  2. Forgetting to override removeEldestEntry for a bounded cache. If you use access-order mode without overriding removeEldestEntry, the map grows without bound — eviction does not happen automatically.

  3. ConcurrentModificationException during iteration. Like HashMap, structurally modifying a LinkedHashMap during iteration (other than via Iterator.remove()) throws ConcurrentModificationException.

  4. Assuming thread safety. LinkedHashMap is not thread-safe. For a concurrent LRU cache, consider a ConcurrentHashMap with explicit eviction logic, or a LinkedHashMap wrapped in a synchronized block.

  5. Confusing access-order and insertion-order get semantics. In access-order mode, get is a structural modification (it moves the entry to the tail), which increments modCount. If an iterator is active, the next call to next() will throw ConcurrentModificationException.

Best Practices

  • Use LinkedHashMap whenever you need HashMap performance but deterministic iteration order (e.g., building HTTP response headers, maintaining pipeline stages in definition order).
  • For an LRU cache, extend LinkedHashMap with accessOrder = true and override removeEldestEntry.
  • Declare variables as Map<K, V> to stay flexible.
  • Use Map.Entry<K, V> iteration (entrySet()) for the most efficient traversal.
  • When thread safety is needed, wrap with Collections.synchronizedMap and synchronize the iteration block explicitly.

Interview Questions

1. How does LinkedHashMap maintain insertion order?

Each entry has before and after pointers in addition to the standard hash-table next pointer. All entries are linked together in a doubly-linked list that tracks insertion (or access) order. The iterator walks this list, not the bucket array, giving ordered O(n) iteration.

2. What is access-order mode and how is it enabled?

Access-order mode is enabled by passing true as the third constructor argument: new LinkedHashMap<>(capacity, loadFactor, true). In this mode, every get, put, or replace moves the accessed entry to the tail of the linked list. The iterator therefore yields entries from least-recently-used to most-recently-used.

3. How do you implement a bounded LRU cache with LinkedHashMap?

Extend LinkedHashMap with accessOrder = true and override removeEldestEntry to return true when size() > maxSize. The LinkedHashMap calls this method after every put; if it returns true, the eldest entry (the head of the list, i.e., the least recently used) is removed automatically.

4. How does LinkedHashMap differ from HashMap?

LinkedHashMap adds a doubly-linked list on top of HashMap, giving ordered iteration. Performance is nearly identical — O(1) average operations — but LinkedHashMap uses slightly more memory per entry for the two extra pointers. HashMap offers no ordering guarantee.

5. Can LinkedHashMap store null keys or values?

Yes. LinkedHashMap inherits HashMap's null-handling: one null key and any number of null values are permitted.

6. Why does get in access-order mode cause ConcurrentModificationException for an active iterator?

In access-order mode, get moves the accessed entry to the tail of the linked list, which is a structural modification that increments modCount. An active fail-fast iterator will detect this change and throw ConcurrentModificationException on its next next() call.

7. When would you choose LinkedHashMap over TreeMap?

Use LinkedHashMap when you need O(1) operations and want to preserve insertion or access order. Use TreeMap when you need entries in sorted (natural or custom) order and O(log n) operations are acceptable. LinkedHashMap also permits null keys; TreeMap does not with natural ordering.

Summary

  • LinkedHashMap is a HashMap augmented with a doubly-linked list for ordered iteration.
  • Default mode is insertion-order; access-order mode (LRU) is enabled via the constructor flag.
  • Override removeEldestEntry to implement a bounded LRU cache.
  • O(1) average performance; slightly more memory per entry than HashMap.
  • Not thread-safe — synchronize externally or use a concurrent alternative.

Continue Learning

Previous: HashMap | Next: TreeMap

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.