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}
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 and when it exceeds 4 we want to delete the oldest entries.
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}
Summary
  • removeEldestEntry by default returns false that means it will not remove any old items.
  • we can implement this method to delete older records.
  • removeEldestEntry is invoked while adding items in the map.
  • removeEldestEntry is useful while implementing data structure similar to Cache.