How to remove Entry from HashMap in Java

Connect with

How to remove Entry from HashMap in JavaYou will be familiar about How to remove entry from HashMap in Java, or it’s implementation class HashMap, Hashtable, LinkedHashMap or ConcurrentHashMap. removing element from map java is very easy for doing so follow this article.

Overview of How to remove entry from HashMap in Java

In day-to-day development you can found the situation where you have to remove element from Map best on the matching of key or value. So, you can use the following way in your real life project. If you don’t know iterating of item in Map 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 from collection , you will encounter ConcurrentModificationException it means your code will throws Exception, 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 element from Map

This is complete working example to remove Entry from Map or you can say removing element from Map in Java, 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.
 */
public class RemoveEntryFromMapExample {

	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 

Java Official site
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 Comment

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