The removeEldestEntry() method of LinkedHashMap is used to automatically remove old entries based on a custom condition. It is mainly used to limit map size and implement cache-like behavior, such as LRU (Least Recently Used) caching.
import java.util.*;
public class LinkedHashMapDemo {
private static final int MAX = 6;
public static void main(String[] args) {
LinkedHashMap<Integer, String> map =
new LinkedHashMap<Integer, String>() {
@Override
protected boolean removeEldestEntry(
Map.Entry<Integer, String> eldest) {
return size() > MAX;
}
};
map.put(0, "Welcome");
map.put(1, "To");
map.put(2, "The");
map.put(3, "World");
map.put(4, "Of");
map.put(5, "geeks");
System.out.println(map);
map.put(6, "GeeksforGeeks");
System.out.println(map);
map.put(7, "Hello");
System.out.println(map);
}
}
Output
{0=Welcome, 1=To, 2=The, 3=World, 4=Of, 5=geeks}
{1=To, 2=The, 3=World, 4=Of, 5=geeks, 6=GeeksforGeeks}
{2=The, 3=World, 4=Of, 5=geeks, 6=GeeksforGeeks, 7=Hello}
Explanation:
- The map is limited to 6 entries using MAX.
- When a new entry causes the size to exceed the limit, the eldest entry is removed.
- Removal happens automatically after insertion.
- Entries are removed in insertion order (default behavior).
Syntax
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
Parameters:
eldest : Represents the eldest entry in the map.
- In insertion-order: least recently inserted entry
- In access-order: least recently accessed entry
If the map contained only one entry before insertion, that entry is both the eldest and newest.
Return Value:
- true : remove the eldest entry
- false : retain the entry
Example: LRU Cache Using Access Order
import java.util.*;
public class GFG {
public static void main(String[] args){
LinkedHashMap<Integer, String> cache
= new LinkedHashMap<Integer, String>(16, 0.75f,
true){
@Override
protected boolean removeEldestEntry(
Map.Entry<Integer, String> eldest)
{
return size() > 3;
}
};
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.get(1);
// Removes least recently used entry
cache.put(4, "D");
System.out.println(cache);
}
}
Output
{3=C, 1=A, 4=D}
Explanation:
- The map uses access order (true in constructor).
- Entry 2 is removed because it is the least recently accessed.
- This behavior mimics a simple LRU cache.