import
java.io.*;
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
System.out.println(
"Going to test the TreeMap LRU "
+
" Cache Implementation"
);
LRUCache cache =
new
LRUCache(
2
);
cache.put(
1
,
10
);
cache.put(
2
,
20
);
System.out.println(
"Value for the key: 1 is "
+ cache.get(
1
));
cache.put(
3
,
30
);
System.out.println(
"Value for the key: 2 is "
+ cache.get(
2
));
cache.put(
4
,
40
);
System.out.println(
"Value for the key: 1 is "
+ cache.get(
1
));
System.out.println(
"Value for the key: 3 is "
+ cache.get(
3
));
System.out.println(
"Value for the key: 4 is "
+ cache.get(
4
));
}
}
class
LRUCache
{
TreeMap<Integer,
int
[]> entries =
new
TreeMap();
HashMap<Integer,
int
[]> map =
new
HashMap();
int
size;
int
count =
0
;
public
LRUCache(
int
capacity)
{
size = capacity;
}
public
int
get(
int
key)
{
if
(map.containsKey(key))
{
int
c = map.get(key)[
1
];
entries.remove(c);
count++;
int
val = map.get(key)[
0
];
entries.put(count,
new
int
[] { key, val });
map.put(key,
new
int
[] { val, count });
return
val;
}
return
-
1
;
}
public
void
put(
int
key,
int
value)
{
if
(map.containsKey(key))
{
int
c = map.get(key)[
1
];
entries.remove(c);
count++;
entries.put(count,
new
int
[] { key, value });
map.put(key,
new
int
[] { value, count });
return
;
}
if
(entries.size() == size)
{
int
lcount = entries.firstKey();
int
[] lkey = entries.get(lcount);
map.remove(lkey[
0
]);
entries.remove(lcount);
}
count++;
entries.put(count,
new
int
[] { key, value });
map.put(key,
new
int
[] { value, count });
}
}