Skip to content

Instantly share code, notes, and snippets.

@serdarmumcu
Created July 30, 2020 18:44
Embed
What would you like to do?
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