Start learning free

LESSON 267 OF 410 · HASH TABLE

LRU Cache in Java in Java

Practice

A cache keeps a few recent results close at hand so they are quick to read again. It can only hold a limited number of entries, so when it is full it must throw one away. An LRU (Least Recently Used) cache throws away the entry that was used longest ago. Build a class LRUCache that stores integer keys with integer values.

The class keeps: private int capacity, a Map<Integer, Integer> called map (key to value) and a List<Integer> called order (the keys, least recently used first).

Create it: new LRUCache(capacity) makes an empty cache that holds at most capacity entries.

Methods and rules:

  • int get(int key) returns the value stored for key. A hit counts as a use: the key becomes the most recently used. If the key is not in the cache (never stored, or already evicted), return -1 and change nothing.
  • void put(int key, int value) stores the value for key, and the key becomes the most recently used.
    • If the key is already in the cache, replace its value. Nothing is evicted.
    • If the key is new and the cache already holds capacity entries, first evict the least recently used entry (remove it from the map and from order), then store the new one.
  • Keep order sorted by use: the least recently used key at the front, the most recently used at the end. Every use moves the key to the end.

Tools for this language:

  • The constructor public LRUCache(int capacity) saves the capacity; the fields are new HashMap<>() and new ArrayList<>().
  • map.containsKey(key) tells whether a key is stored; map.put(key, value) stores or replaces a value; map.remove(key) deletes an entry; map.size() counts the entries.
  • order.remove(Integer.valueOf(key)) removes an item by value (a plain int would be read as an index), order.add(key) adds at the end, and order.get(0) with order.remove(0) reads and removes the first item.

This version walks over the list of keys for each operation, which is fine for learning. Interview solutions reach O(1) with a hash map plus a doubly linked list.

You start with the code that tests your class (write LRUCache above it):

class Solution {
    public void mainFunction() {
        LRUCache c = new LRUCache(2);
        c.put(1, 10);
        c.put(2, 20);
        System.out.println("Get 1: " + c.get(1));
        c.put(3, 30);
        System.out.println("Get 2: " + c.get(2));
        System.out.println("Get 3: " + c.get(3));
        System.out.println("Miss 9: " + c.get(9));
        c.put(1, 11);
        System.out.println("Update 1: " + c.get(1));
        c.put(4, 40);
        System.out.println("Evicted 3: " + c.get(3));
        System.out.println("Kept 1: " + c.get(1));
        System.out.println("Kept 4: " + c.get(4));
        LRUCache s = new LRUCache(1);
        s.put(1, 100);
        s.put(2, 200);
        System.out.println("Small 1: " + s.get(1));
        System.out.println("Small 2: " + s.get(2));
    }
}

Expected output:

Get 1: 10
Get 2: -1
Get 3: 30
Miss 9: -1
Update 1: 11
Evicted 3: -1
Kept 1: 11
Kept 4: 40
Small 1: -1
Small 2: 200

Check it against the rules: Get 2 is -1 because key 2 was the least recently used when key 3 arrived (key 1 had just been read). Updating key 1 to 11 does not evict anything. With capacity 1, the second put evicts the first key.


Two structures work together: the map gives a fast lookup of the value, and order remembers which key was used when. Both must always hold the same keys.

order.remove(Integer.valueOf(key)) then order.add(key) moves a key to the end. order.get(0) is the least recently used key.

class LRUCache {
    private int capacity;
    private Map<Integer, Integer> map = new HashMap<>();
    private List<Integer> order = new ArrayList<>();

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        if (!map.containsKey(key)) return -1;
        order.remove(Integer.valueOf(key));
        order.add(key);
        return map.get(key);
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            order.remove(Integer.valueOf(key));
        } else if (map.size() >= capacity) {
            int evict = order.get(0);
            order.remove(0);
            map.remove(evict);
        }
        map.put(key, value);
        order.add(key);
    }
}

STEP 1 OF 19
    Ctrl + Enter to check

    Lru Cache in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free