Check whether a HashSet is empty or not in Java

Java 8Object Oriented ProgrammingProgramming

To check whether a HashSet is empty or not, use the isEmpty() method.

Create a HashSet −

HashSet hs = new HashSet();

Add elements to the HashSet −

hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
hs.add("N");

Now, check whether the HashSet is empty or not. Since we added elements above, it won’t be empty −

hs.isEmpty();

The following is an example that checks whether a HashSet is empty or not −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println("Elements: "+hs);
      System.out.println("Is the set empty? = "+hs.isEmpty());
   }
}

Output

Elements: [A, B, C, D, E, F, K, M, N]
Is the set empty? = false

Let us see another example −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // empty set
      System.out.println("Is the set empty? = "+hs.isEmpty());
   }
}

Output

Is the set empty? = true
raja
Published on 11-Jan-2019 16:50:55
Advertisements