Java – How to delete all entries of HashMap ?

In this article, we will discuss how to remove all entries from invoking HashMap

1. HashMap :

  • clear() –> to delete all entries present in HashMap
  • Note: above method inherited from Map interface

2. Removing all entries from HashMap

RemoveAllEntrriesOfHashMap.java

package in.bench.resources.java.map;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class RemoveAllEntrriesOfHashMap {

	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 all elements
		hashMap.clear();

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

		// getting entrySet() into Set
		Set<Entry<String, String>> entrySet = hashMap.entrySet();

		// for-each loop
		for(Entry<String, String> entry : entrySet) {
			System.out.println("Key : "  + entry.getKey() + "\t\t"
					+ "Value : "  + entry.getValue());
		}

		// HashMap contents
		System.out.println("\n\nHashMap contents after clearing: "
				+ hashMap);
	}
}

Output:

Size of a HashMap is : 5

Before any operation : Set of all Entries: 

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

HashMap size after clearing : 0

HashMap contents after clearing: {}

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to check whether a particular key is present in HashMap ?
Java - How to delete an entry of HashMap ?