Simple LRU Cache in Java: Explanation & Practice
Implement a simple LRU cache
Problem summary
Implement a cache that removes least recently used item when capacity is exceeded.
Starter code
import java.util.*;
// Use LinkedHashMap with access order
public class Main {
public static void main(String[] args) {
// Cache with capacity 3
// Add items and show eviction
}
}Expected output and test cases
- A evicted when D added
Cache: {B=2, C=3, D=4} - B evicted, A accessed
Cache: {A=1, C=3, D=4} - Single item cache
Cache: {X=1}
Hints
- LinkedHashMap with accessOrder=true
- Override removeEldestEntry()
- Return true when size > capacity
Related Collections exercises
- Practice Sort Map by Value in Java
- Practice Group By Property in Java
- Practice Priority Queue with Custom Order in Java
Practice all Collections exercises · Run this idea in the Java compiler