Java HashMap.isEmpty()
In this tutorial, we will learn about the Java HashMap.isEmpty() function, and learn how to use this function to check if this HashMap is empty or not, with the help of examples.
isEmpty()
HashMap.isEmpty() returns true if this map contains no key-value mappings, or false if this map contains one or more key-value mappings.
The syntax of isEmpty() function is
isEmpty()
Returns
The function returns boolean value.
Examples
1. HashMap isEmpty() for an empty HashMap
In this example, we will initialize a HashMap hashMap with no mappings in it. To check if this hashMap is emtpy, call isEmpty() method on this HashMap. Since the haspMap is empty, isEmpty() should return true.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
boolean result = hashMap.isEmpty();
System.out.println("Is the HashMap empty? " + result);
}
}
Output
Is the HashMap empty? true
2. HashMap isEmpty() for an non-empty HashMap
In this example, we will initialize a HashMap hashMap with four mappings in it. To check if this hashMap is emtpy, call isEmpty() method on this HashMap. Since the haspMap is not empty, isEmpty() should return false.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "A");
hashMap.put(2, "B");
hashMap.put(3, "C");
hashMap.put(4, "D");
boolean result = hashMap.isEmpty();
System.out.println("Is the HashMap empty? " + result);
}
}
Output
Is the HashMap empty? false
3. isEmpty() – When HashMap is null
In this example, we will initialize a HashMap hashMap with null value. To check if this hashMap is emtpy, call isEmpty() method on this HashMap. Since the haspMap is null, isEmpty() should throw java.lang.NullPointerException.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = null;
boolean result = hashMap.isEmpty();
System.out.println("Is the HashMap empty? " + result);
}
}
Output
Exception in thread "main" java.lang.NullPointerException
at Example.main(Example.java:7)
Conclusion
In this Java Tutorial, we have learnt the syntax of Java HashMap.isEmpty() function, and also learnt how to use this function with the help of examples.
