Last Updated : 11 Jul, 2025
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
Java
// 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());
}
}
The Mappings are: {Java=1, Language=3, Programming=2} Is the map empty? falseSyntax of isEmpty() Method
public boolean isEmpty()
Return Type:
Example 2: Check isEmpty() Before and After Adding Entries
Java
// 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());
}
}
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
// 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());
}
}
The Mappings are: {} Is the map empty? true
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4