Start learning free

LESSON 368 OF 671 · HASH TABLE

LRU Cache in Java: A HashMap Plus an ArrayList of Keys

Practice Read the full explanation

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

    JAVA · HASH TABLE

    Lru Cache in Java, explained

    Problem overview

    A cache holds a limited number of entries. When it is full and a new key arrives, something has to go. An LRU (Least Recently Used) cache evicts the entry that was used longest ago, where "used" means read with get or written with put.

    The class LRUCache stores int keys and int values and has three parts:

    • the constructor LRUCache(int capacity), which makes an empty cache;
    • int get(int key), which returns the stored value, or -1 for a key that is missing or was evicted. A hit makes the key the most recently used; a miss changes nothing;
    • void put(int key, int value), which stores the value and makes the key the most recently used. Updating an existing key evicts nothing. Adding a new key to a full cache first evicts the least recently used entry.

    The lesson's test code makes a cache of capacity 2, puts keys 1 and 2, reads key 1, then puts key 3. Key 2 is now the oldest, so it is the one evicted: get(2) prints -1 while get(1) and get(3) still work.

    Approach: one structure for values, one for recency

    A single collection can't do both jobs well in this version, so the class keeps two that always hold the same keys:

    • map, a Map<Integer, Integer>, answers "what is the value for this key?" and "is this key stored?";
    • order, a List<Integer>, holds the keys sorted by use: the least recently used at index 0, the most recently used at the end.

    Every use takes the key out of its current place in order and adds it at the end. Eviction is then simple: the key at index 0 is the victim. It must be removed from both structures, or the two would disagree.

    Finding a key inside an ArrayList means walking the list, so get and put cost time proportional to the number of entries. That is fine for learning how the rules fit together. Faster designs replace the list with a structure that can move a key in constant time, but they follow the same rules.

    Step by step

    1. Declare the class LRUCache and close its brace right away; everything else goes inside.
    2. Add the capacity field as a private int. The constructor fills it in.
    3. Add map as a private Map<Integer, Integer> starting as a new HashMap. It stores each key's value.
    4. Add order as a private List<Integer> starting as a new ArrayList. Its position in the list is the only record of how recently a key was used.
    5. Write the constructor and, inside it, save the argument with this.capacity = capacity. The this. separates the field from the parameter of the same name.
    6. Start get as a public method taking key and returning an int.
    7. Handle a miss first: if the map doesn't contain the key, return -1 and touch nothing.
    8. Remove the key from order using Integer.valueOf(key). The wrapper matters, as the language notes below explain.
    9. Add the key back at the end of order: it is now the most recently used.
    10. Return the value that the map holds for the key.
    11. Start put as a public void method taking key and value.
    12. Handle an update: if the map already contains the key, take it out of order, as get does. There is no eviction, because the cache doesn't grow.
    13. Handle a new key in a full cache with an else if whose condition is map.size() >= capacity.
    14. Read the oldest key with order.get(0) into an int named evict.
    15. Remove index 0 from order with order.remove(0).
    16. Remove evict from the map. Removing it from order alone would leave its value behind and make the map count too high.
    17. Store the value with map.put(key, value), after the whole if chain, because every put stores, whether the key is new or not.
    18. Add the key at the end of order, also after the chain, so every put marks its key as the most recently used.

    The solution in Java

    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);
        }
    }
    
    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));
        }
    }
    

    The Java details worth a closer look:

    • remove(int) against remove(Object). List has two remove methods. Given a plain int, it removes the element at that position. Given an Integer, it removes the first element equal to it. On a list holding [5, 6, 7], remove(Integer.valueOf(7)) leaves [5, 6], remove(1) leaves [5, 7], and remove(7) throws an IndexOutOfBoundsException because there is no position 7. That is why the key is wrapped, while order.remove(0) deliberately uses the position version.
    • Autoboxing. order.add(key) and map.put(key, value) accept int values and box them into Integer objects. int evict = order.get(0) and return map.get(key) unbox them again. The unboxing in get is safe because the method has already confirmed that the key is present: map.get returns null for a missing key, and unboxing null would throw a NullPointerException.
    • Private fields with initialisers. The two collections are created where they are declared, so every new LRUCache gets its own empty ones. The constructor only has to save the capacity.
    • The order of the if chain. The else if runs only for a key that isn't in the map, so the size check never triggers an eviction for an update.

    Complexity

    Time: O(n) per operation, where n is the number of entries (at most capacity). The map operations take constant time on average, but order.remove(Integer.valueOf(key)) scans the list to find the key, and removing from the front of an ArrayList shifts every other element left. A sequence of m operations therefore costs O(m * n) in the worst case.

    Space: O(n). The map and the list each hold at most capacity keys.

    Edge cases and common mistakes

    • A miss must not reorder anything. get(9) on a cache that never stored 9 returns -1 and leaves order as it was.
    • An update is a use. With order equal to [1, 3], calling put(1, 11) changes the order to [3, 1]. Key 3 is now the next victim, so the following put(4, 40) evicts it, and get(3) afterwards gives -1.
    • Forgetting the map when evicting. If only order loses the evicted key, get would still return its value, and map.size() would stay at capacity forever.
    • Capacity 1. Each new key evicts the previous one: after put(1, 100) and put(2, 200), get(1) is -1 and get(2) is 200.
    • Capacity 0. The lesson doesn't cover it. With this solution, the first put finds the map "full", calls order.get(0) on an empty list and throws an IndexOutOfBoundsException.
    • Using remove(key) without Integer.valueOf. It compiles, but removes by position, so the wrong key (or none, with an exception) leaves the list.

    Testing

    Tracing the lesson's first cache, with order and map shown after each call:

    CallResultordermap
    put(1, 10)[1]{1=10}
    put(2, 20)[1, 2]{1=10, 2=20}
    get(1)10[2, 1]{1=10, 2=20}
    put(3, 30)[1, 3]{1=10, 3=30}
    get(2)-1[1, 3]{1=10, 3=30}
    get(3)30[1, 3]{1=10, 3=30}
    get(9)-1[1, 3]{1=10, 3=30}
    put(1, 11)[3, 1]{1=11, 3=30}
    put(4, 40)[1, 4]{1=11, 4=40}

    The full output of the lesson's test code is:

    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
    
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free