Java Utility Library

Java LinkedHashMap - removeEldestEntry() Method



The java.util.LinkedHashMap.removeEldestEntry() method returns true if this map should remove its eldest entry. This method is invoked by put and putAll after inserting a new entry into the map. It provides the implementor with the opportunity to remove the eldest entry each time a new one is added. This is useful if the map represents a cache: it allows the map to reduce memory consumption by deleting stale entries.

Syntax

protected boolean removeEldestEntry(Map.Entry<K,V> eldest)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

eldest The least recently inserted entry in the map, or if this is an access-ordered map, the least recently accessed entry. This is the entry that will be removed it this method returns true. If the map was empty prior to the put or putAll invocation resulting in this invocation, this will be the entry that was just inserted; in other words, if the map contains a single entry, the eldest entry is also the newest.

Return Value

Returns true if the eldest entry should be removed from the map; false if it should be retained.

Exception

NA

Example:

In the example below, the java.util.LinkedHashMap.removeEldestEntry() method is used to check whether the given map should remove its eldest entry or not.

import java.util.*;

public class MyClass {
  private static final int MAX_ENTRIES = 4;

  public static void main(String[] args) {
    //creating a linkedhashmap
    LinkedHashMap<Integer, String> MyMap = new LinkedHashMap<Integer, String>(){
      protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
        return size() > MAX_ENTRIES;
      }
    };

    //populating the map
    //as the size of the map increase more than
    //MAX_ENTRIES, removeEldestEntry method is
    //called to remove eldest entry
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");
    MyMap.put(105, "Sam");
    MyMap.put(106, "Ramesh");

    //printing the content of the map
    System.out.println("MyMap contains: " + MyMap);
  }
}

The output of the above code will be:

MyMap contains: {103=Kim, 104=Jo, 105=Sam, 106=Ramesh}

❮ Java.util - LinkedHashMap