How to delete an entry of HashMap

In this article, we will discuss how to remove a particular entry from invoking HashMap

 

HashMap :

  • remove(key) –> to delete a particular entry by specifying key as argument
  • Note: above method inherited from Map interface

 

Removing an entry from HashMap

RemoveEntryOfHashMap.java

package in.bench.resources.java.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class RemoveEntryOfHashMap {

	public static void main(String[] args) {

		// creating HashMap object of type <String, String>
		HashMap<String, String> hashMap = new HashMap<String, String>(); 

		// adding key-value pairs to HashMap object
		hashMap.put("Google", "Sundar Pichai");
		hashMap.put("Facebook", "Mark Zuckerberg");
		hashMap.put("LinkedIn", "Reid Hoffman");
		hashMap.put("Apple", "Steve Jobs");
		hashMap.put("Microsoft", "Bill Gates");

		System.out.println("Size of a HashMap is : "
				+ hashMap.size());

		System.out.println("\n\nBefore any operation :"
				+ " Set of all Entries: \n");

		// getting keySet() into Set
		Set<String> set1 = hashMap.keySet();

		// for-each loop
		for(String key : set1) {
			System.out.println("Key : "  + key + "\t\t" 
					+ "Value : "  + hashMap.get(key));
		}

		// deleting particular entry
		hashMap.remove("Google");

		System.out.println("\n\nHashMap size after removing : "
				+ hashMap.size());

		System.out.println("\n\nAfter remove operation :"
				+ " Set of all Entries: \n");

		// getting keySet() into Set
		Set<String> set2 = hashMap.keySet();

		// Collection Iterator
		Iterator<String> itr = set2.iterator();

		while(itr.hasNext()) {
			String key = itr.next();
			System.out.println("Key : "  + key + "\t\t" 
					+ "Value : "  + hashMap.get(key));
		}
	}
}

Output:

Size of a HashMap is : 5


Before any operation : Set of all Entries: 

Key : LinkedIn		Value : Reid Hoffman
Key : Microsoft		Value : Bill Gates
Key : Facebook		Value : Mark Zuckerberg
Key : Apple		Value : Steve Jobs
Key : Google		Value : Sundar Pichai


HashMap size after removing : 4


After remove operation : Set of all Entries: 

Key : LinkedIn		Value : Reid Hoffman
Key : Microsoft		Value : Bill Gates
Key : Facebook		Value : Mark Zuckerberg
Key : Apple		Value : Steve Jobs

 

References:

 

Happy Coding !!
Happy Learning !!

How to delete all entries of HashMap
Iterating Map using forEach() in Java 8