LRU Cache with LinkedHashMap
javaJavainterview-prepintermediatejava
A least-recently-used cache in a dozen lines: a LinkedHashMap in access order that removes its eldest entry when it grows past the capacity.
import java.util.*;
public class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
public LruCache(int capacity) {
super(16, 0.75f, true); // true = order by access, not by insertion
this.capacity = capacity;
}
// Called after every put: returning true removes the least recently used entry.
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
public static void main(String[] args) {
LruCache<String, Integer> cache = new LruCache<>(3);
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);
cache.get("a"); // "a" is now the most recently used
cache.put("d", 4); // over capacity: "b" is evicted
System.out.println(cache.keySet()); // [c, a, d]
System.out.println(cache.containsKey("b")); // false
System.out.println(cache.get("c")); // 3
System.out.println(cache.keySet()); // [a, d, c]
}
}