File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ package learnCollections ;
2+
3+ import java .util .LinkedHashMap ;
4+ import java .util .Map ;
5+
6+ public class LRUCache <K , V > extends LinkedHashMap <K , V > {
7+ private int capacity ;
8+
9+ LRUCache (int capacity ) {
10+ super (capacity , 0.75f , true );
11+ this .capacity = capacity ;
12+ }
13+
14+ // invoke when put or putAll is called
15+ @ Override
16+ protected boolean removeEldestEntry (Map .Entry <K , V > eldest ) {
17+ return size () > capacity ;
18+ }
19+
20+ public static void main (String [] args ) {
21+ LRUCache <String , Integer > studentMap = new LRUCache <>(3 );
22+ studentMap .put ("Bob" , 99 );
23+ studentMap .put ("Alice" , 89 );
24+ studentMap .put ("Ram" , 91 );
25+ studentMap .get ("Bob" );
26+ studentMap .put ("Rahul" , 89 );
27+
28+ System .out .println (studentMap ); // {Ram=91, Bob=99, Rahul=89}
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments