Adds LRU cache

master
Abhinav Sarkar 2019-06-28 14:15:26 +05:30
parent d84f4bad8d
commit 4973ae6b73
1 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,74 @@
package net.abhinavsarkar.algorist;
import java.util.Iterator;
import java.util.Optional;
public class LRUCache<K,V>
{
private final LRWCache<K,V> store;
public LRUCache(int capacity) {
this.store = new LRWCache<>(capacity);
}
public Optional<V> get(K key)
{
Optional<V> val = store.get(key);
val.ifPresent(v -> put(key, v));
return val;
}
public void remove(K key)
{
store.remove(key);
}
public void put(K key, V val)
{
store.put(key, val);
}
public int size()
{
return store.size();
}
public Iterator<K> iterator()
{
return store.iterator();
}
@Override
public String toString()
{
return store.toString();
}
public static void main(String[] args)
{
LRUCache<String, String> cache = new LRUCache<>(4);
cache.put("a", "abhinav");
cache.put("b", "batman");
cache.put("c", "carol");
cache.put("z", "zellman");
System.out.println(cache);
cache.put("w", "walker");
System.out.println(cache);
cache.put("c", "carly");
System.out.println(cache);
cache.put("x", "xander");
System.out.println(cache);
cache.get("w");
System.out.println(cache);
cache.put("a", "abhinav");
System.out.println(cache);
}
}