LinkedHashMap and LinkedHashSet in Java
- 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.
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
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 } }
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.
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 } }
[2, 3, 1]
[3, 1, 4]
false
LinkedHashSet — Insertion-Order Set
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] } }
[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.
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.