1. What are LinkedHashSet and LinkedHashMap?
The Java standard library provides several implementations of Set and Map. The most well‑known are HashSet and HashMap. These structures provide fast hash‑based access to elements, but they do not guarantee any order when iterating. When traversal order matters, LinkedHashSet and LinkedHashMap come to the rescue.
- LinkedHashSet is a Set that remembers the order in which elements were added.
- LinkedHashMap is a Map that remembers the order in which key–value pairs were added (or, optionally, access order).
They are implemented like “regular” HashSet/HashMap, but augmented with a doubly linked list to store the order of elements.
2. Insertion order and access order
Insertion order
By default, LinkedHashSet and LinkedHashMap guarantee that during iteration the elements are returned in the order they were added (for‑each/iterator).
Set<String> set = new LinkedHashSet<>();
set.add("A");
set.add("B");
set.add("C");
for (String s : set) {
System.out.println(s);
}
// Output: A B C
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
for (Integer key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}
// Output: 1 -> one, 2 -> two, 3 -> three
Access order (LinkedHashMap only)
LinkedHashMap has a mode for last access order (access order). If you pass true as the third constructor parameter when creating the map, then on each access to an entry (get/put) it moves to the end of the list.
Map<Integer, String> lruMap = new LinkedHashMap<>(16, 0.75f, true);
lruMap.put(1, "one");
lruMap.put(2, "two");
lruMap.put(3, "three");
lruMap.get(2); // Accessing key 2
for (Integer key : lruMap.keySet()) {
System.out.println(key);
}
// Output: 1 3 2 (2 is last because it was accessed)
LRU cache via removeEldestEntry
The key feature of LinkedHashMap is the simple implementation of an LRU cache (Least Recently Used, “least recently used”). You only need to override removeEldestEntry(Map.Entry<K,V> eldest): if it returns true, the “oldest” entry is removed when a new one is added.
class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int maxSize;
public LRUCache(int maxSize) {
super(maxSize, 0.75f, true); // true — access order
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxSize;
}
}
// Usage:
LRUCache<Integer, String> cache = new LRUCache<>(3);
cache.put(1, "one");
cache.put(2, "two");
cache.put(3, "three");
cache.get(1); // Make 1 the "freshest"
cache.put(4, "four"); // 2 will be removed (the oldest one)
System.out.println(cache.keySet()); // [3, 1, 4]
3. Memory and performance: LinkedHashSet/LinkedHashMap vs HashSet/HashMap
How it works
Internally, it’s almost like a regular HashSet/HashMap, but each entry is also stored in a doubly linked list. This additional structure “remembers” insertion/access order.
Memory cost
Because of the prev/next references on each node, more memory is required. For millions of entries this is noticeable; for typical tasks it’s a reasonable price to pay for deterministic order.
Performance cost
Basic add/lookup/remove operations remain amortized O(1). Iteration is slightly slower due to traversing the list, but in most cases the difference is minimal. And the “remove the oldest” scenario (LRU) is implemented very efficiently, since the oldest entry is always at the head of the list.
Bottom line: if order matters — choose LinkedHashSet/LinkedHashMap. If you need to save memory and don’t need order — HashSet/HashMap are sufficient.
4. Caching, deterministic output, stable tests
Caching (LRU)
LinkedHashMap is an ideal foundation for caches with a size limit and automatic eviction of “old” entries. It’s used in libraries/frameworks, when working with files, images, and computed results.
Deterministic output
For reports, export, and serialization, where a predictable data representation is critical, use LinkedHashSet/LinkedHashMap. This is especially important for tests — the order doesn’t shuffle from run to run.
Stable tests
In unit tests, expected collections are often compared with actual ones. If the order isn’t guaranteed, tests can be flaky. With “linked” implementations, determinism ensures stability.
Example: comparing HashMap and LinkedHashMap
Map<Integer, String> hashMap = new HashMap<>();
Map<Integer, String> linkedMap = new LinkedHashMap<>();
for (int i = 1; i <= 5; i++) {
hashMap.put(i, "val" + i);
linkedMap.put(i, "val" + i);
}
System.out.println(hashMap.keySet()); // Order may be arbitrary!
System.out.println(linkedMap.keySet()); // Always 1, 2, 3, 4, 5
5. LinkedList vs ArrayDeque for queues
LinkedList
- Implements the List, Deque, and Queue interfaces.
- Doubly linked list: fast inserts/removals at the head and tail.
- Can be used as a queue (FIFO), a stack (LIFO), and a double‑ended queue.
ArrayDeque
- Implements Deque and Queue (but not List).
- Array‑backed, automatically resizes.
- Often faster than LinkedList for queue/stack operations; less overhead.
- Does not support the null element.
When to use which?
- Queues and stacks — almost always ArrayDeque.
- Many inserts/removals in the middle and you also need a list — LinkedList.
- Set/Map with order — LinkedHashSet/LinkedHashMap.
Example: task queue
Queue<String> queue = new ArrayDeque<>();
queue.add("task1");
queue.add("task2");
System.out.println(queue.poll()); // task1
Example: stack
Deque<String> stack = new ArrayDeque<>();
stack.push("first");
stack.push("second");
System.out.println(stack.pop()); // second
Summary:
— For queues and stacks — ArrayDeque.
— For a list with frequent middle inserts — LinkedList.
— For Set/Map with order — LinkedHashSet/LinkedHashMap.
6. Common mistakes when working with LinkedHashSet/LinkedHashMap
Error #1: Expecting HashSet/HashMap to preserve order.
HashSet/HashMap do not guarantee order. If it matters — use LinkedHashSet/LinkedHashMap.
Error #2: Using LinkedHashMap for a cache without overriding removeEldestEntry.
For LRU you must override removeEldestEntry, otherwise the map will grow without bounds.
Error #3: Using LinkedList for queues/stacks without necessity.
In most cases, ArrayDeque is faster and more memory‑efficient.
Error #4: Expecting LinkedHashMap to sort entries.
LinkedHashMap preserves insertion/access order but does not sort by key. For sorting — use TreeMap.
Error #5: Adding null to ArrayDeque.
ArrayDeque does not support null elements — it will throw NullPointerException.
Error #6: Comparing collections without accounting for order.
When comparing LinkedHashSet/LinkedHashMap with regular HashSet/HashMap, take the differences in element order into account.
GO TO FULL VERSION