JavaData StructuresIntermediate

LinkedHashMap

A HashMap subclass that maintains a doubly-linked list running through its entries, preserving insertion order or access order.

Review the syntaxStudy the examplesOpen the coding app
new LinkedHashMap<K, V>()
new LinkedHashMap<K, V>(int initialCapacity, float loadFactor, boolean accessOrder)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

A HashMap subclass that maintains a doubly-linked list running through its entries, preserving insertion order or access order.

A `LinkedHashMap` in Java is an implementation of the `Map` interface that extends `HashMap` but adds the capability to maintain the order of its entries. It achieves this by using a doubly-linked list that runs through all of its entries. By default, it maintains *insertion order*, meaning elements are iterated in the order they were first inserted into the map. Alternatively, it can be configured to maintain *access order* (least-recently accessed to most-recently accessed), which is useful for implementing LRU (Least Recently Used) caches. Like `HashMap`, `LinkedHashMap` provides O(1) average time complexity for `put()`, `get()`, `remove()`, and `containsKey()` operations. The overhead of maintaining the linked list is minimal, typically only slightly higher than `HashMap`. It allows one `null` key and multiple `null` values. `LinkedHashMap` is not thread-safe; for concurrent access, `Collections.synchronizedMap()` or `ConcurrentHashMap` (if order is not critical) should be used. It's the ideal choice when you need the fast performance of a hash map combined with predictable iteration order.

Quick reference

Syntax

new LinkedHashMap<K, V>()
new LinkedHashMap<K, V>(int initialCapacity, float loadFactor, boolean accessOrder)

Inputs

Parameters

initialCapacity (optional)int · The initial capacity of the LinkedHashMap.
loadFactor (optional)float · The load factor for the LinkedHashMap.
accessOrder (optional)boolean · If true, the map orders its entries by access order (LRU). If false, it orders by insertion order.

See it in practice

Examples

1

Maintaining insertion order (default behavior)

import java.util.LinkedHashMap;

LinkedHashMap<String, Integer> insertionOrderMap = new LinkedHashMap<>();
insertionOrderMap.put("Apple", 1);
insertionOrderMap.put("Banana", 2);
insertionOrderMap.put("Cherry", 3);
insertionOrderMap.put("Apple", 4); // Update value, but key's insertion order remains

System.out.println("Insertion order: " + insertionOrderMap);
Output:
Insertion order: {Apple=4, Banana=2, Cherry=3}

Iterating over the `LinkedHashMap` returns elements in the order they were initially inserted. Updating a key's value does not change its position.

2

Using access order for LRU cache behavior

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

// Create an LRU cache with a max capacity of 3
LinkedHashMap<String, Integer> lruCache = new LinkedHashMap<String, Integer>(16, 0.75f, true) {
    @Override
    protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
        return size() > 3; // Remove oldest entry if size exceeds 3
    }
};

lruCache.put("A", 1);
lruCache.put("B", 2);
lruCache.put("C", 3);
System.out.println("Initial: " + lruCache); // {A=1, B=2, C=3}

lruCache.get("A"); // Access A, moves it to the end (most recent)
System.out.println("After get A: " + lruCache); // {B=2, C=3, A=1}

lruCache.put("D", 4); // Add D, B (eldest) is removed
System.out.println("After put D: " + lruCache); // {C=3, A=1, D=4}

lruCache.put("E", 5); // Add E, C (eldest) is removed
System.out.println("After put E: " + lruCache); // {A=1, D=4, E=5}
Output:
Initial: {A=1, B=2, C=3} After get A: {B=2, C=3, A=1} After put D: {C=3, A=1, D=4} After put E: {A=1, D=4, E=5}

Configures `LinkedHashMap` for access order (`true`) and overrides `removeEldestEntry()` to implement a simple LRU cache. Accessing an element moves it to the end of the iteration order.

3

Iterating over entries in order

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

LinkedHashMap<String, String> config = new LinkedHashMap<>();
config.put("server", "localhost");
config.put("port", "8080");
config.put("user", "admin");

System.out.println("Configuration entries:");
for (Map.Entry<String, String> entry : config.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
Output:
Configuration entries: server: localhost port: 8080 user: admin

Demonstrates iterating through the map's entries, confirming that the insertion order is preserved.

Debug faster

Common Errors

1

Confusing insertion order with sorted order

Cause: `LinkedHashMap` maintains insertion order (or access order), not a sorted order based on keys' natural comparison or a `Comparator`. If you need sorted keys, `TreeMap` is the correct choice.

Fix: Use `LinkedHashMap` when you need predictable iteration order based on insertion or access. Use `TreeMap` when you need elements to be sorted lexicographically or by a custom `Comparator`.

import java.util.LinkedHashMap;
import java.util.TreeMap;

LinkedHashMap<String, Integer> linkedMap = new LinkedHashMap<>();
linkedMap.put("Banana", 2);
linkedMap.put("Apple", 1);
linkedMap.put("Cherry", 3);
System.out.println("LinkedHashMap (insertion order): " + linkedMap); // {Banana=2, Apple=1, Cherry=3}

TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Banana", 2);
treeMap.put("Apple", 1);
treeMap.put("Cherry", 3);
System.out.println("TreeMap (sorted order): " + treeMap); // {Apple=1, Banana=2, Cherry=3}

Runtime support

Compatibility

JVMN/AJava 1.4+

Source: Oracle Java Documentation

Common questions

Frequently Asked Questions

A HashMap subclass that maintains a doubly-linked list running through its entries, preserving insertion order or access order.

initialCapacity: The initial capacity of the LinkedHashMap. loadFactor: The load factor for the LinkedHashMap. accessOrder: If true, the map orders its entries by access order (LRU). If false, it orders by insertion order.

Confusing insertion order with sorted order: Use `LinkedHashMap` when you need predictable iteration order based on insertion or access. Use `TreeMap` when you need elements to be sorted lexicographically or by a custom `Comparator`.