Access Order Mode: The accessOrder Parameter
What you'll learn: How to configure a LinkedHashMap to automatically reorder entries based on access, not just insertion order.
By default, LinkedHashMap maintains insertion order—the order in which you put entries into the map. But there's a special mode that reorders entries every time you access them: access order mode.
What Is Access Order Mode?
Access order mode makes your map behave like a usage log. Every time you read an entry (using get() or getOrDefault()), that entry moves to the end of the iteration order. The least recently accessed entries drift toward the front.
Think of it like a browser's "Recently Viewed" list—every time you view a page, it jumps to the top (or end, in LinkedHashMap's case).
Enabling Access Order
Use the three-argument constructor:
LinkedHashMap<String, Integer> accessMap =
new LinkedHashMap<>(initialCapacity, loadFactor, true);
The third parameter, accessOrder, is a boolean:
false(default): insertion order modetrue: access order mode
Example Behavior
LinkedHashMap<String, String> map =
new LinkedHashMap<>(16, 0.75f, true);
map.put("A", "Apple");
map.put("B", "Banana");
map.put("C", "Cherry");
map.get("A"); // Access "A" — it moves to the end
// Iteration order now: B, C, A
Accessing "A" moved it to the end. The map now reflects access history, not insertion history.
Why Use This?
Access order mode is perfect for LRU caches (Least Recently Used), where you want to track and potentially evict the least-used entries.
Key Takeaway: Use new LinkedHashMap<>(capacity, loadFactor, true) to enable access order mode, where reading entries reorders them, making the map track usage history instead of insertion history.