75 lines
1.4 KiB
Java
75 lines
1.4 KiB
Java
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);
|
|
}
|
|
|
|
|
|
}
|