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

  1. LinkedHashMap with accessOrder=true
  2. Override removeEldestEntry()
  3. Return true when size > capacity

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler