When to use LinkedHashMap.removeEldestEntry method

removeEldestEntry method exists only on subclasses of LinkedHashMap
removeEldestEntry always invoked after an element is inserted. Based on what this method returns following action will happen if method returns true based on some condition, then the oldest entry will be removed. if method always returns true then basically list will be empty. if method return false, then nothing will be deleted and map will behave like any other LinkedHashMap. after every put or putAll insertion, the eldest element will be removed, no matter what. The JavaDoc shows a very sensible example on how to use it:
Lets see an example of removeEldestEntry.
MapRemoveEntry Example
import java.util.LinkedHashMap;
import java.util.Map;

public class MapRemoveEntry {

	public static void main(String argv[]) {

		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>() {
			private static final long serialVersionUID = 1L;

			protected boolean removeEldestEntry(Map.Entry<Integer,String> 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.forEach((k,v) -> { System.out.println("key = " + k + " value = " + v);});
If we run the above example we will get following output.
key = 1 value = B
key = 2 value = C
key = 3 value = D
key = 4 value = E
Reason is, method removeEldestEntry returns true when the map size is >4. That means when the map size is greater than 4 => the oldest entry will be removed. In this case oldest is the very first entry with (key=0, value=A).


Using removeEldestEntry we can control when to remove the most oldest entry from the map. This can be used for creating a cache.