Created
August 8, 2017 05:33
-
-
Save watsh-rajneesh/b60e03417ebcf2d6fcfeac01d4f8adc6 to your computer and use it in GitHub Desktop.
LRU Cache implementation with linked hash map.
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 edu.sjsu.watsh.algos; | |
import java.util.ArrayList; | |
import java.util.LinkedHashMap; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* Implement LRU cache using linked hash map. | |
* | |
* @author rwatsh on 8/7/17. | |
*/ | |
public class LRUCache { | |
private Map<String, Object> cache = new LinkedHashMap<>(); | |
private int capacity = Integer.MAX_VALUE; | |
public LRUCache(int capacity) { | |
this.capacity = capacity; | |
} | |
public Object get(String key) { | |
if (cache.get(key) != null) { | |
Object value = cache.get(key); | |
synchronized (LRUCache.class) { | |
if (cache.get(key) != null) { | |
cache.remove(key); | |
cache.put(key, value); | |
} | |
} | |
return value; | |
} | |
return null; | |
} | |
public void put(String key, Object value) { | |
if (cache.get(key) == null) { | |
if (cache.size() >= capacity) { | |
List<Object> list = new ArrayList<>(cache.values()); | |
cache.remove(list.get(0)); | |
} | |
cache.put(key, value); // add it to the end. | |
} else { | |
// value exists, so remove and add it back with the updated value | |
cache.remove(key); | |
cache.put(key, value); | |
} | |
} | |
@Override | |
public String toString() { | |
return cache.values().toString(); | |
} | |
public static void main(String[] args) { | |
LRUCache cache = new LRUCache(5); | |
cache.put("1", "1"); | |
cache.put("2", "2"); | |
cache.put("3", "3"); | |
cache.put("4", "4"); | |
System.out.println(cache); | |
cache.put("5", "5"); | |
cache.put("6", "6"); | |
System.out.println(cache); | |
cache.get("5"); | |
System.out.println(cache); | |
cache.get("2"); | |
System.out.println(cache); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment