How to use removeEldestEntry() Method in Java


Table of Content

removeEldestEntry() Method in Java

LinkedHashMap in Java stores key-value pairs and maintains the order of elements inserted. LinkedHashMap extends HashMap. Method removeEldestEntry in LinkedHashMap is used to delete the old entry in the map automatically. This method is triggered when we put values to the map.
removeEldestEntry() method is triggered when we put new items to map. It is a boolean method and accepts one parameter. We can override this method to decide whether and when to remove eldest entries from the map.

Examples

LinkedHashMap Simple
Following is a simple LinkedHashMap which is created with initial size 10. And then later added 6 Items to it. When we print the map it prints {0=A, 1=B, 2=C, 3=D, 4=E, 5=F}
LinkedHashMap map;
map = new LinkedHashMap(10 , 0.7f, false);
map.put(0, "A"); 
map.put(1, "B"); 
map.put(2, "C"); 
map.put(3, "D"); 
map.put(4, "E"); 
map.put(5, "F");

System.out.println(map); //{0=A, 1=B, 2=C, 3=D, 4=E, 5=F}
LinkedHashMap with removeEldestEntry
Here we implement the protected method removeEldestEntry and return true if size is more than 4. As a result this map will automatically delete one of the oldest entry when its size becomes more than 4. That's why even though we are adding 6 items to it, when we print we get only 4 items like {2=C, 3=D, 4=E, 5=F}
LinkedHashMap map;

map = new LinkedHashMap(10 , 0.7f, false) {
  protected boolean removeEldestEntry(Map.Entry eldest) {
    return size()>4;
  }
};

map.put(0, "A"); 
map.put(1, "B"); 
map.put(2, "C"); 
map.put(3, "D"); 
map.put(4, "E"); 
map.put(5, "F");

System.out.println(map); //{2=C, 3=D, 4=E, 5=F}
Notes
  • LinkedHashMap maintains the insertion order of the values.
  • If removeEldestEntry returns false then no items will ever be removed from the map and it will essentially behave like a normal Map.
  • If removeEldestEntry returns true then it will not let any item's get added to the map.
  • removeEldestEntry is a protected method that's why we can only implement it while creating the map.

No comments :

Post a Comment

Please leave your message queries or suggetions.