How to remove Entry from HashMap in Java

Connect with

Oracle Java
Well, sometimes interviewer asked you , how to remove any Entry/record from Map, or its implementation class HashMap, Hashtable, LinkedHashMap or ConcurrentHashMap. In day-to-day development you can found the situation where you have to remove from Map best on the matching of key or value. So you can use the following way in your real life project. I prefer , if you don’t know how to iterate HashMap in java , first go through prior post to understand how to iterate over HashMap.

When you try to remove while iterating same collection , you will encounter ConcurrentModificationException it means your code will throws , to avoid this ConcurrentModificationException . You have to use Iterator’s remove method for removing/deleting from collection/Map ( HashMap, Hashtable, LinkedHashMap or ConcurrentHashMap ). We use entrySet() for performance reason, but we can use Iterator’s remove() method for deleting entries from Map.

Example to remove from Map/HashMap

This is complete working example to remove Entry from Map if matched .


package com.mysoftkey.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * This java class is used to demonstrate ,
 * how to remove entry from map if key matched.
 * 
 * @author Ranjeet Jha
 *
 */
public class RemoveEntryFromMapExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		Map  map = new HashMap();
		map.put("IN", "India");
		map.put("USA", "United States Of America");
	
		Iterator> iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
		   Map.Entry entry = iterator.next();
		   System.out.printf("Key : %s , Value: %s %n", entry.getKey(), entry.getValue());
		   
		   // if value "India" matched then remove.
		   if ("India".equals(entry.getValue())) {
		    iterator.remove(); 
		   }
		}
		
		System.out.println("---------------------------------------");
		// iterate map to check whether deleted/removed or not
		for (Map.Entry entry : map.entrySet()) {
			System.out.printf("Key : %s , Value: %s %n", entry.getKey(), entry.getValue());
		}
	}

}

Output of Example


Key : USA , Value: United States Of America 
Key : IN , Value: India 
---------------------------------------
Key : USA , Value: United States Of America 

Suggestions are welcome to improve this post. cheers Happy Learning 🙂


Connect with

1 thought on “How to remove Entry from HashMap in Java

  1. Pingback: sweta

Leave a Reply

Your email address will not be published. Required fields are marked *