<code>LinkedHashMap</code> in Java β Insertion-Ordered Map
LinkedHashMap is a HashMap that additionally maintains a doubly-linked list over its entries. Iteration visits entries in insertion order by default, or access order if you enable it β the building block of a simple LRU cache.
Basics
var cfg = new LinkedHashMap<String, String>();
cfg.put("host", "db.local");
cfg.put("port", "5432");
cfg.put("user", "admin");
cfg.forEach((k, v) -> System.out.println(k + "=" + v));
// host=db.local
// port=5432
// user=admin β always in insertion order
Access order β LRU cache
// initialCapacity, loadFactor, accessOrder
var cache = new LinkedHashMap<String, byte[]>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) {
return size() > 100; // bounded to 100 entries
}
};
cache.put("a", dataA);
cache.put("b", dataB);
cache.get("a"); // moves 'a' to most recently used
cache.put("c", dataC);
// When size exceeds 100, removeEldestEntry drops the LRU automatically
Performance
Same O(1) average as HashMap. Extra memory: two pointers per entry (prev/next) and a slightly larger iteration overhead β typically <10%.
Common mistakes
- Using
HashMapthen being surprised by order β iteration isn't guaranteed. Switch toLinkedHashMap. - Expecting a thread-safe LRU β
LinkedHashMapisn't. Wrap inCollections.synchronizedMap, or use Caffeine/Guava for production caches. - Mixing access order and iteration β a
getduring iteration modifies the order, which can confuse the iterator.
Related
Pillar: Java collections. Siblings: HashMap, TreeMap.