Skip to content

Instantly share code, notes, and snippets.

@serdarmumcu
Created July 30, 2020 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serdarmumcu/7693ca5103362a23ad8f1b6537cb1521 to your computer and use it in GitHub Desktop.
Save serdarmumcu/7693ca5103362a23ad8f1b6537cb1521 to your computer and use it in GitHub Desktop.
LRU Cache Java Implementation
package com.yazilimmimari.hackerrank;
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<S,T> {
LinkedHashMap<S,T> cache;
int capacity;
LRUCache(int capacity) {
cache = new LinkedHashMap<>(capacity);
this.capacity = capacity;
}
T get(S key) {
if(!cache.containsKey(key))
return null;
T val = cache.remove(key);
cache.put(key,val);
return val;
}
void put(S key, T value) {
if(cache.containsKey(key))
cache.remove(key);
else if(cache.size() == capacity)
{
Map.Entry<S,T> entry = cache.entrySet().iterator().next();
cache.remove(entry.getKey());
}
cache.put(key,value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment