Showing posts with label removeEldestEntry. Show all posts
How to use removeEldestEntry() Method in Java
March 05, 2019
Java
Map
removeEldestEntry
Table of Content
LinkedHashMap
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.
removeEldestEntry : What it does
Say we want to only keep certain numbers of items in the LinkedHashMap, and when it reaches the upper limit we want to get rid of the oldest entries, how do we do it. We can write our custom method to delete oldest entry when we notice that map.size() == upper_limit.
And call that method to delete old entries before adding any items to the map. removeEldestEntry does the same thing it allows us to implement similar logic without writing boilerplate code.
removeEldestEntry is checked by Java before adding any items to the map.
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}