Write a Java program to remove all the mappings from a map


This is a Java program that demonstrates how to remove all elements from a HashMap. Here's how it works:

  • First, a HashMap object is created using the HashMap class. This HashMap will be used to store integer keys and string values.
  • Key-value pairs are added to the HashMap using the put() method.
  • The contents of the HashMap are printed to the console using the println() method.
  • The clear() method is used to remove all elements from the HashMap.
  • The contents of the HashMap are printed again to the console using the println() method.

Source Code

import java.util.*;  
public class RemoveAll
{  
	public static void main(String args[])
	{
		HashMap <Integer,String> hash_map = new HashMap <Integer,String> ();
		hash_map.put(1, "Pink");
		hash_map.put(2, "Green");
		hash_map.put(3, "Red");
		hash_map.put(4, "White");
		hash_map.put(5, "Blue");
		hash_map.put(6, "Black");
		hash_map.put(7, "Orange");		
		System.out.println("The Original linked map : " + hash_map);
 
		hash_map.clear();// Removing all the elements
		System.out.println("The New map : " + hash_map);
	}
}

Output

The Original linked map : {1=Pink, 2=Green, 3=Red, 4=White, 5=Blue, 6=Black, 7=Orange}
The New map : {}