Popular Tutorials
Start Learning JavaCertification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Java HashMap isEmpty()
The Java HashMap isEmpty() method checks if the hashmap is empty.
The syntax of the isEmpty() method is:
hashmap.isEmpty()
Here, hashmap is an object of the HashMap class.
isEmpty() Parameters
The isEmpty() method does not take any parameters.
isEmpty() Return Value
- returns
trueif the hashmap does not contain any key/value mappings - returns
falseif the hashmap contains key/value mappings
Example: Check if HashMap is Empty
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create an HashMap
HashMap<String, Integer> languages = new HashMap<>();
System.out.println("Newly Created HashMap: " + languages);
// checks if the HashMap has any element
boolean result = languages.isEmpty(); // true
System.out.println("Is the HashMap empty? " + result);
// insert some elements to the HashMap
languages.put("Python", 1);
languages.put("Java", 14);
System.out.println("Updated HashMap: " + languages);
// checks if the HashMap is empty
result = languages.isEmpty(); // false
System.out.println("Is the HashMap empty? " + result);
}
}
Output
Newly Created HashMap: {}
Is the HashMap empty? true
Updated HashMap: {Java=14, Python=1}
Is the HashMap empty? false
In the above example, we have created a hashmap named languages. Here, we have used the isEmpty() method to check whether the hashmap contains any elements or not.
Initially, the newly created hashmap does not contain any element. Hence, isEmpty() returns true. However, after we add some elements (Python, Java), the method returns false.
Also Read:
Did you find this article helpful?