beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to check if a HashMap is empty or not?

By Chaitanya Singh | Filed Under: Java.util package

Description

Program to check if a HashMap is empty or not. We are using isEmpty() method of HashMap class to perform this check.

Program

import java.util.HashMap;
class HashMapIsEmptyExample{

  public static void main(String args[]) {
 
    // Create a HashMap
    HashMap<Integer, String> hmap = new HashMap<Integer, String>(); 
 
 
    // Checking whether HashMap is empty or not
    /* isEmpty() method signature and description -
     * public boolean isEmpty(): Returns true if this map 
     * contains no key-value mappings.
     */
    System.out.println("Is HashMap Empty? "+hmap.isEmpty());
 
    // Adding few elements
    hmap.put(11, "Jack");
    hmap.put(22, "Rock");
    hmap.put(33, "Rick");
    hmap.put(44, "Smith");
    hmap.put(55, "Will");
 
    // Checking again
    System.out.println("Is HashMap Empty? "+hmap.isEmpty());
  } 
}

Output:

Is HashMap Empty? true
Is HashMap Empty? false

Enjoyed this post? Try these related posts

  1. Delete all the elements from HashSet
  2. Iterate a LinkedList in reverse sequential order – java
  3. Clone a HashMap in Java
  4. How to copy one Set to another Set
  5. How to Iterate over a Set/HashSet
  6. HashMap – Get value from key example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap