Skip to content
Home Java LinkedHashMap and LinkedHashSet in Java

LinkedHashMap and LinkedHashSet in Java

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Collections → Topic 9 of 21
Java LinkedHashMap and LinkedHashSet explained — insertion-order iteration, access-order LRU cache, when to use over HashMap and HashSet.
⚙️ Intermediate — basic Java knowledge assumed
In this tutorial, you'll learn
Java LinkedHashMap and LinkedHashSet explained — insertion-order iteration, access-order LRU cache, when to use over HashMap and HashSet.
  • LinkedHashMap maintains insertion order; HashMap does not.
  • Pass accessOrder=true to LinkedHashMap constructor for LRU semantics.
  • Override removeEldestEntry() to implement a bounded LRU cache in 10 lines.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

LinkedHashMap and LinkedHashSet maintain insertion order — iteration yields elements in the order they were added. LinkedHashMap also supports access-order mode, where recently accessed entries move to the tail — the foundation of an LRU cache. They have the same O(1) average complexity as HashMap and HashSet with a small memory overhead for the doubly-linked list.

LinkedHashMap — Insertion Order

Example · JAVA
1234567891011121314151617181920212223
package io.thecodeforge.java.collections;

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

public class LinkedHashMapDemo {
    public static void main(String[] args) {
        // Insertion-order map
        Map<String, Integer> scores = new LinkedHashMap<>();
        scores.put("Alice", 95);
        scores.put("Charlie", 88);
        scores.put("Bob", 92);

        // Iteration order = insertion order — always
        scores.forEach((name, score) ->
            System.out.println(name + ": " + score));
        // Alice: 95
        // Charlie: 88
        // Bob: 92

        // HashMap would print in some arbitrary order — not predictable
    }
}
▶ Output
Alice: 95
Charlie: 88
Bob: 92

LRU Cache Using Access-Order LinkedHashMap

Pass true as the third constructor argument (accessOrder=true) and override removeEldestEntry to cap the size. This is a textbook LRU cache.

Example · JAVA
123456789101112131415161718192021222324252627282930313233
package io.thecodeforge.java.collections;

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

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

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true);  // accessOrder = true
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;  // evict when over capacity
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(3);
        cache.put(1, "one");
        cache.put(2, "two");
        cache.put(3, "three");
        System.out.println(cache.keySet()); // [1, 2, 3]

        cache.get(1);  // access 1 — moves to tail (most recently used)
        System.out.println(cache.keySet()); // [2, 3, 1]

        cache.put(4, "four");  // capacity exceeded — removes 2 (least recently used)
        System.out.println(cache.keySet()); // [3, 1, 4]
        System.out.println(cache.containsKey(2)); // false — evicted
    }
}
▶ Output
[1, 2, 3]
[2, 3, 1]
[3, 1, 4]
false

LinkedHashSet — Insertion-Order Set

Example · JAVA
12345678910111213141516171819202122
package io.thecodeforge.java.collections;

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetDemo {
    public static void main(String[] args) {
        Set<String> visited = new LinkedHashSet<>();
        visited.add("/home");
        visited.add("/about");
        visited.add("/home");   // duplicate — ignored
        visited.add("/contact");

        System.out.println(visited);  // [/home, /about, /contact]
        // Order preserved, duplicates removed

        // Deduplication while preserving order
        String[] input = {"banana", "apple", "banana", "cherry", "apple"};
        Set<String> deduped = new LinkedHashSet<>(java.util.Arrays.asList(input));
        System.out.println(deduped);  // [banana, apple, cherry]
    }
}
▶ Output
[/home, /about, /contact]
[banana, apple, cherry]

🎯 Key Takeaways

  • LinkedHashMap maintains insertion order; HashMap does not.
  • Pass accessOrder=true to LinkedHashMap constructor for LRU semantics.
  • Override removeEldestEntry() to implement a bounded LRU cache in 10 lines.
  • LinkedHashSet deduplicates while preserving insertion order.
  • Memory overhead vs HashMap/HashSet: one extra prev/next pointer per entry.

Interview Questions on This Topic

  • QHow does LinkedHashMap differ from HashMap?
  • QHow would you implement an LRU cache using Java's built-in classes?
  • QWhen is LinkedHashSet preferable to HashSet?

Frequently Asked Questions

When should I use LinkedHashMap instead of HashMap?

When iteration order matters — building an ordered JSON response, preserving URL parameter order, displaying results in insertion order, or testing where you need predictable output. If order does not matter, HashMap is slightly faster.

Is LinkedHashMap thread-safe?

No, like HashMap. Wrap it with Collections.synchronizedMap() for basic thread safety, but this does not protect iteration. For a thread-safe LRU cache in production, use Caffeine or Guava's Cache instead.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousIterator and ListIterator in JavaNext →PriorityQueue in Java
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged