Write a Java program to check whether a map contains key-value mappings (empty) or not


This is a Java program that demonstrates how to check if a HashMap is empty or not. 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 isEmpty() method is used to check if the HashMap is empty or not. The result is stored in a boolean variable, res.
  • The contents of the boolean variable res are printed to the console using the println() method.
  • The clear() method is used to remove all elements from the HashMap.
  • The isEmpty() method is used again to check if the HashMap is empty or not. The result is stored in the same boolean variable, res.
  • The contents of the boolean variable res are printed to the console again using the println() method.

Source Code

import java.util.*;  
public class Check_EmptyNot
{  
	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");	
 
		boolean res = hash_map.isEmpty();
 
		System.out.println("Is Hashmap Empty : " + res);
		hash_map.clear();
 
		res = hash_map.isEmpty();// check if map is empty
 
		System.out.println("Is Hashmap Empty : " + res);
	}
}

Output

Is Hashmap Empty : false
Is Hashmap Empty : true