Java solution using LinkedHashMap

  • 10
    import java.util.*;
    public class LRUCache {
        LinkedHashMap<Integer, Integer> cache;
        public LRUCache(int capacity) {
          cache = new LinkedHashMap<Integer, Integer>(){
          protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            if(cache.size() > capacity) {
              return true;
            return false;
        public int get(int key) {
          if(cache.containsKey(key)) {
            int value = cache.get(key);
            return value;
          return -1;
        void moveToFront(int key) {
          int val = cache.get(key);
        public void set(int key, int value) { 
          cache.put(key, value);

  • 0

    why removeEldestEntry need to be overridden? it's defined as this:

       removeEldestEntry(Map.Entry<K,V> eldest)

    Returns true if this map should remove its eldest entry. Does this mean each time I declare a LinkedHashMap this method need to be overridden? Thanks for answering.

  • 1

    You have to override it in order to specify that you want to remove the eldest entry once you've hit the max capacity defined by the constructor.
    If you do not override, this method will always return false by default, as defined in the the Java source code.

  • 0

    Is there a way I can call removeEldestEntry and save the eldest entry to DataBase?

  • 0

    @manzoor you can use cache.keySet(), it is in the order you want!

  • 0

    This is vary nice solution in Java, space and time!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.