Mastery
Mastery/Java/C. Collections framework
T2 · intermediate depth

HashMap vs LinkedHashMap vs TreeMap ordering guarantees

Three maps, three different ordering guarantees: HashMap gives none at all (don't rely on any observed order -- it can even change between runs). LinkedHashMap preserves insertion order by default -- and has a lesser-known access-order mode that reorders on every get, the exact building block an LRU cache is made from. TreeMap keeps keys sorted at all times.

java
import java.util.*;

Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
for (String k : List.of("banana", "apple", "cherry", "date")) {
    hash.put(k, k.length());
    linked.put(k, k.length());
    tree.put(k, k.length());
}
System.out.println("HashMap (no guaranteed order):   " + hash.keySet());
System.out.println("LinkedHashMap (insertion order): " + linked.keySet());
System.out.println("TreeMap (sorted order):          " + tree.keySet());

LinkedHashMap's access-order mode -- the exact mechanism an LRU cache builds on:

java
// the `true` third argument switches to access-order -- every get() moves that key to the end
Map<String, Integer> accessOrder = new LinkedHashMap<>(16, 0.75f, true);
accessOrder.put("a", 1);
accessOrder.put("b", 2);
accessOrder.put("c", 3);
accessOrder.get("a");
System.out.println("after get(\"a\") in access-order mode: " + accessOrder.keySet() + "  <- \"a\" moved to the end");

Interview angle

"Implement an LRU cache" is one of the most common interview exercises in the industry, and the elegant solution is a LinkedHashMap in access-order mode with removeEldestEntry overridden — candidates who know this solve it in a few lines; candidates who don't end up hand-rolling a doubly-linked list plus a hash map from scratch. Recognizing when the "hard" data-structure question has a one-line stdlib answer is itself a valuable signal.

In the industry

Choosing the wrong Map implementation is a real, if quiet, bug source — code that implicitly depends on HashMap's iteration order (which can silently change between JVM versions or even between runs) is fragile in a way that's easy to miss until it breaks. TreeMap is reached for specifically when sorted iteration is a genuine requirement, not a default; LinkedHashMap is the pragmatic middle ground whenever deterministic order (either insertion or access) actually matters for correctness.