Java HashMap isEmpty() Method
The isEmpty() method in Java HashMap class is used to check whether the map contains any key-value mappings.
Example 1: Checking isEmpty() after adding entries to the map
// Mapping integer value to string keys
import java.util.HashMap;
public class Geeks {
public static void main(String[] args)
{
// Creating an empty HashMap
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
// Mapping int values to string keys
hm.put("Java", 1);
hm.put("Programming", 2);
hm.put("Language", 3);
// Displaying the HashMap
System.out.println("The Mappings are: " + hm);
// Checking for the emptiness of Map
System.out.println("Is the map empty? "
+ hm.isEmpty());
}
}
Output
The Mappings are: {Java=1, Language=3, Programming=2} Is the map empty? false
Syntax of isEmpty() Method
public boolean isEmpty()
Return Type:
- It returns true, if the map contains no key-value mapping.
- It returns false, if the map has one or more key-value mapping.
Example 2: Check isEmpty() Before and After Adding Entries
// Mapping String value to integer keys
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Create an empty HashMap
HashMap<Integer, String> map = new HashMap<>();
// Display the HashMap
System.out.println("HashMap contents: "
+ map);
// Check if the map is empty
System.out.println("Is the map empty? "
+ map.isEmpty());
// Add key-value pairs
map.put(1, "Java");
map.put(2, "Programming");
map.put(3, "Language");
// Display the updated HashMap
System.out.println("Updated HashMap contents: "
+ map);
// Check if the map is empty again
System.out.println("Is the map empty? "
+ map.isEmpty());
}
}
Output
HashMap contents: {} Is the map empty? true Updated HashMap contents: {1=Java, 2=Programming, 3=Language} Is the map empty? false
Example 3: Check isEmpty() on an Empty HashMap
// Java program to demonstrate the working of isEmpty()
import java.util.HashMap;
class Geeks {
public static void main(String[] args)
{
// Creating an empty HashMap
HashMap<String, Integer> hm = new HashMap<>();
// Displaying the HashMap
System.out.println("The Mappings are: " + hm);
// Checking for the emptiness of Map
System.out.println("Is the map empty? "
+ hm.isEmpty());
}
}
Output
The Mappings are: {} Is the map empty? true