Maps: LinkedHashMap in access order is an LRU cache

The three-argument LinkedHashMap constructor plus an overridden removeEldestEntry gives a fixed-size least-recently-used cache in a few lines.

Code
class Lru<K, V> extends LinkedHashMap<K, V> {
    private final int cap;
    Lru(int cap) { super(16, 0.75f, true); this.cap = cap; }
    @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > cap; }
}

var cache = new Lru<String, Integer>(3);
cache.put("a", 1); cache.put("b", 2); cache.put("c", 3);
cache.get("a");                      // touching "a" makes "b" the eldest
cache.put("d", 4);                   // evicts "b"

System.out.println(cache.keySet());
Output
[c, a, d]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30