In this article, we will discuss and understand with a program to check whether HashMap is empty or not
In earlier article, we have seen how to check whether HashMap contains particular key/value or Not ? Read below articles for more details with example
- How to check whether a particular key is present in HashMap
- How to check whether a particular value is present in HashMap
To check whether HashMap is empty or not :
Method signature:
public boolean isEmpty();
- Above method is used to check whether HashMap is empty or not from invoking Map object
- It can be HashMap or LinkedHashMap or TreeMap
- Returns true, if Map is empty
- otherwise return false
HashMapIsEmptyOrNot.java
package in.bench.resources.collection; import java.util.HashMap; public class HashMapIsEmptyOrNot { public static void main(String[] args) { // creating empty HashMap object of type <String, String> HashMap<String, String> hashMap = new HashMap<String, String>(); // checking empty even before adding any Key-Value pairs boolean isEmpty1 = hashMap.isEmpty(); System.out.println("1. Checking Empty" + " before adding any entries : " + isEmpty1); // adding key-value pairs to HashMap object hashMap.put("Google", "Sundar Pichai"); hashMap.put("Facebook", "Mark Zuckerberg"); hashMap.put("LinkedIn", "Reid Hoffman"); hashMap.put("Apple", "Steve Jobs"); hashMap.put("Microsoft", "Bill Gates"); // checking empty adding few entries boolean isEmpty2 = hashMap.isEmpty(); System.out.println("\n2. Checking Empty" + " before adding any entries : " + isEmpty2); } }
Output:
1. Checking Empty before adding any entries : true 2. Checking Empty before adding any entries : false
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
- http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
- https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html
Happy Coding !!
Happy Learning !!