Table of Content
LinkedHashMap
LinkedHashMap in Java stores key-value pairs and maintains the order of elements inserted. LinkedHashMap extends HashMap.
The 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 a certain number of items in the LinkedHashMap, and when it reaches the upper limit we want to get rid of the oldest entries.
We could write a custom method to delete the oldest entry when
map.size() == upper_limit
and call it before adding any items.
removeEldestEntry
does the same thing, allowing us to implement this logic without boilerplate code.
removeEldestEntry
is checked by Java before adding any items to the map.
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}
Example 2 : LinkedHashMap with removeEldestEntry
In the following example, we want to keep only 4 items in the map. When it exceeds 4, the oldest entries should be deleted.
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}
Summary
removeEldestEntry
by default returns false, meaning it will not remove any old items.- We can implement this method to delete older records.
removeEldestEntry
is invoked while adding items to the map.- It is useful for implementing data structures similar to a cache.
No comments :
Post a Comment
Please leave your message queries or suggetions.
Note: Only a member of this blog may post a comment.