When to use LinkedHashMap.removeEldestEntry
method
removeEldestEntry
method exists only on subclasses of LinkedHashMap
.
How it works
removeEldestEntry
is always invoked after an element is inserted.- Based on the method’s return value:
- Returns true: The oldest entry is removed.
- Always returns true: The map continuously removes entries (will become empty).
- Returns false: Nothing is removed; behaves like a normal LinkedHashMap.
After every put
or putAll
insertion, the eldest element may be removed depending on the logic. The JavaDoc provides a clear example of this usage.
Example: removeEldestEntry
import java.util.LinkedHashMap;
import java.util.Map;
public class MapRemoveEntry {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
@Override
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));
}
}
Output:
key = 1 value = B
key = 2 value = C
key = 3 value = D
key = 4 value = E
key = 2 value = C
key = 3 value = D
key = 4 value = E
Explanation: The method removeEldestEntry
returns true when the map size is greater than 4. This removes the oldest entry (key=0, value=A).
Summary
Using removeEldestEntry
, you can control when to remove the oldest entry from a map. This is particularly useful for implementing caches where you want to limit the number of stored items.
No comments :
Post a Comment
Please leave your message queries or suggetions.
Note: Only a member of this blog may post a comment.