Monday 18 October 2021

Java: Remove oldest entry from the map

A Map is an object that maps keys to values. A map does not contain duplicate keys: Each key can map to at most one value.

 


 

In the above table, roll number is the key, which maps to student name. for example, roll Number 123 maps to the student name Krishna, 126 maps to the student name Kiran.

 

How to remove oldest entry from the map?

By overriding removeEldestEntry method of LinkedHashMap class, we can enforce a policy for removing stale mappings automatically when new mappings are added to the map.

 

Signature

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

 

This method returns true if this map should remove its eldest entry.

 

Example

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

	@Override
	protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
		return this.size() > MAX_ELEMENTS;
	}
};

 

Find the below working application.

 

RemoveEldestEntry.java

 

package com.sample.app.collections;

import java.util.LinkedHashMap;
import java.util.Map;

public class RemoveEldestEntry {

	private static final int MAX_ELEMENTS = 5;

	public static void main(String args[]) {
		Map<Integer, String> map = new LinkedHashMap<Integer, String>() {
			private static final long serialVersionUID = 1L;

			@Override
			protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
				return this.size() > MAX_ELEMENTS;
			}
		};

		map.put(1, "One");
		map.put(2, "Two");
		map.put(3, "Three");
		map.put(4, "Four");
		map.put(5, "Five");

		System.out.println("Entries in map are : " + map);

		System.out.println("Add one more element to the map");
		map.put(6, "Six");

		System.out.println("Entries in map are : " + map);
	}

}

Output

Entries in map are : {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Add one more element to the map
Entries in map are : {2=Two, 3=Three, 4=Four, 5=Five, 6=Six}

 

You may like

Interview Questions

NumberFormatException Explained

Initial heap size set to a larger value than the maximum heap size

Is below statement compile?

Versioning History of Java

Understanding ConcurrentModificationException in Java

No comments:

Post a Comment