English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java HashMap isEmpty() method checks if the hash map is empty.
The syntax of isEmpty() method is:
hashmap.isEmpty()
isEmpty() method without any parameters.
If the hash map does not contain anyKey/ValueIf the mapping is present, return true
If the hash map containsKey/ValueIf the mapping is not present, return false
import java.util.HashMap; class Main { public static void main(String[] args) { //Create HashMap HashMap<String, Integer> languages = new HashMap<>(); System.out.println("The newly created HashMap: " + languages); //Check if the HashMap contains any elements boolean result = languages.isEmpty(); // true System.out.println("Is HashMap empty? ", + result); //Insert some elements into the HashMap languages.put("Python", 1); languages.put("Java", 14); System.out.println("Updated HashMap: ", + languages); //Check if HashMap is Empty result = languages.isEmpty(); // false System.out.println("Is HashMap empty? ", + result); } }
Output Result
Newly created HashMap: {} Is HashMap empty? true Updated HashMap: {Java=14, Python =1} Is HashMap empty? false
In the above example, we created a hash map named languages. Here, we used the isEmpty() method to check if the hash map contains any elements.
Initially, the newly created hash map does not contain any elements. Therefore, isEmpty() returns true. However, after adding some elements (Python,JavaAfter that, the method returns false.