Java HashSet.isEmpty() – Examples
In this tutorial, we will learn about the Java HashSet.isEmpty() method, and learn how to use this method to check if a HashSet is empty or not, with the help of examples.
isEmpty()
HashSet.isEmpty() returns true if this HahSet contains no elements, and false if this HashSet contains atleast one element.
Syntax
The syntax of isEmpty() method is
HashSet.isEmpty()
Returns
The function returns boolean value of true or false.
Example 1 – isEmpty()
In this example, we will define an empty HashSet and programmatically check if the HashSet is empty or not using isEmpty() method.
Java Program
import java.util.HashSet;
public class Example {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<String>();
boolean result = hashSet.isEmpty();
System.out.println("Is HashSet empty? " + result);
}
}
Output
Is HashSet empty? true
Example 2 – isEmpty() – Non-empty HashSet
In this example, we will define an HashSet with one element, and programmatically check if the HashSet is empty or not using isEmpty() method.
Java Program
import java.util.HashSet;
public class Example {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<String>();
hashSet.add("a");
boolean result = hashSet.isEmpty();
System.out.println("Is HashSet empty? " + result);
}
}
Output
Is HashSet empty? false
Conclusion
In this Java Tutorial, we have learnt the syntax of Java HashSet.isEmpty() method, and also learnt how to use this method with the help of Java examples.