How to implement LRU Cache in Java

Caching is an important need in most of Applications. Let’s see how to implement an LRU cache in Java. LinkedHashMap is the key to implement, which provides a way to achieve the LRU functionality.

Let’s see the code

package com.codezuzu.cache;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K,V> extends LinkedHashMap<K, V>{

  private int capacity;

  public LRUCache(int initialCapacity) {
    capacity = initialCapacity;

  protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
    return this.size() > capacity;

  public static void main(String[] args) {
    LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(10);

    for (int i = 0; i < 20; i++) {
     cache.put(i, i);


The key to achieve LRU functionality is to implement removeEldestEntry() API. We maintain a variable which is out max cache size. Whenever the Cache size exceeds the max, the oldest entry is removed.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.