LRU Cache Java Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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