This version is solved via a LinkedHashMap. LinkedHashMap maintains a built-in doubly-linked list and hashtable, i.e. LRU character is built inside a LinkedHashMap.
JDK 1.8 docs says:1
2
3
4
51. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). ...
2. A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). ...
3. The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
new in JDK 1.8: protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
: returns true
if this map should remove its eldest entry.
1 | class LRUCache { |
Attention that remove()
takes in a key
parameter.
Lazier: (via JDK 1.8 APIs):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22class LRUCache {
private LinkedHashMap<Integer, Integer> map;
private final int size;
public LRUCache(int capacity) {
size = capacity;
map = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > size;
}
};
}
public int get(int key) {
return map.getOrDefault(key, -1);
}
public void put(int key, int value) {
map.put(key, value);
}
}