How to Check If a Set Is Empty in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a Set in Java is empty. We will explore the standard isEmpty() method, a simple and efficient way to determine if a set contains any elements.

You will also learn how to verify the size of a set using the size() method and understand how to handle potential NullPointerException when dealing with null sets. By the end of this lab, you will be proficient in checking the emptiness of Java sets under various scenarios.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/hashset("HashSet") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/if_else -.-> lab-559975{{"How to Check If a Set Is Empty in Java"}} java/collections_methods -.-> lab-559975{{"How to Check If a Set Is Empty in Java"}} java/hashset -.-> lab-559975{{"How to Check If a Set Is Empty in Java"}} java/object_methods -.-> lab-559975{{"How to Check If a Set Is Empty in Java"}} end

Use isEmpty() for Set Check

In this step, we will learn how to check if a Set in Java is empty using the isEmpty() method. A Set is a collection that cannot contain duplicate elements. The isEmpty() method is a simple and efficient way to determine if a collection contains any elements.

  1. First, let's create a new Java file named SetCheck.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing SetCheck.java.

  2. Open the SetCheck.java file in the editor and add the following code:

    import java.util.HashSet;
    import java.util.Set;
    
    public class SetCheck {
    
        public static void main(String[] args) {
            // Create a new HashSet
            Set<String> fruits = new HashSet<>();
    
            // Check if the set is empty using isEmpty()
            boolean isEmptyBeforeAdd = fruits.isEmpty();
            System.out.println("Is the fruits set empty before adding elements? " + isEmptyBeforeAdd);
    
            // Add some elements to the set
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            // Check if the set is empty after adding elements
            boolean isEmptyAfterAdd = fruits.isEmpty();
            System.out.println("Is the fruits set empty after adding elements? " + isEmptyAfterAdd);
        }
    }

    Let's break down the new parts of this code:

    • import java.util.HashSet; and import java.util.Set;: These lines import the necessary classes to work with Set and HashSet.
    • Set<String> fruits = new HashSet<>();: This line creates a new HashSet object named fruits. We specify <String> to indicate that this set will store String objects.
    • boolean isEmptyBeforeAdd = fruits.isEmpty();: This line calls the isEmpty() method on the fruits set and stores the result (either true or false) in a boolean variable named isEmptyBeforeAdd.
    • fruits.add("Apple");: This line adds the string "Apple" to the fruits set.
    • boolean isEmptyAfterAdd = fruits.isEmpty();: This line checks if the set is empty again after adding elements.
  3. Save the SetCheck.java file (Ctrl+S or Cmd+S).

  4. Now, let's compile the Java program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Then, run the following command:

    javac SetCheck.java

    If the compilation is successful, you will not see any output.

  5. Finally, run the compiled program using the java command:

    java SetCheck

    You should see output similar to this:

    Is the fruits set empty before adding elements? true
    Is the fruits set empty after adding elements? false

    This output confirms that the isEmpty() method correctly reported the state of the set before and after adding elements.

Verify Set Size with size()

In the previous step, we learned how to check if a Set is empty using isEmpty(). Another common operation is to find out how many elements are in a Set. For this, we use the size() method. The size() method returns the number of elements currently in the set.

  1. Open the SetCheck.java file in your ~/project directory in the WebIDE editor.

  2. Modify the main method to include calls to the size() method. Replace the existing main method with the following code:

    import java.util.HashSet;
    import java.util.Set;
    
    public class SetCheck {
    
        public static void main(String[] args) {
            // Create a new HashSet
            Set<String> fruits = new HashSet<>();
    
            // Check the size of the set before adding elements
            int sizeBeforeAdd = fruits.size();
            System.out.println("Size of the fruits set before adding elements: " + sizeBeforeAdd);
    
            // Add some elements to the set
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            // Check the size of the set after adding elements
            int sizeAfterAdd = fruits.size();
            System.out.println("Size of the fruits set after adding elements: " + sizeAfterAdd);
    
            // Add a duplicate element (Sets do not allow duplicates)
            fruits.add("Apple");
    
            // Check the size again
            int sizeAfterDuplicateAdd = fruits.size();
            System.out.println("Size of the fruits set after adding a duplicate: " + sizeAfterDuplicateAdd);
        }
    }

    Here's what we added:

    • int sizeBeforeAdd = fruits.size();: This line calls the size() method on the fruits set and stores the returned integer value (the number of elements) in a variable named sizeBeforeAdd.
    • int sizeAfterAdd = fruits.size();: This checks the size after adding the initial three elements.
    • fruits.add("Apple");: We attempt to add "Apple" again. Since "Apple" is already in the set, this operation will not change the set's contents.
    • int sizeAfterDuplicateAdd = fruits.size();: This checks the size after attempting to add a duplicate.
  3. Save the SetCheck.java file.

  4. Compile the modified Java program in the Terminal:

    javac SetCheck.java

    Again, no output indicates successful compilation.

  5. Run the program:

    java SetCheck

    You should see output similar to this:

    Size of the fruits set before adding elements: 0
    Size of the fruits set after adding elements: 3
    Size of the fruits set after adding a duplicate: 3

    This output shows that the size() method correctly reports the number of elements, and that adding a duplicate element does not increase the size of the set.

Handle Null Sets

In the previous steps, we worked with a Set that was properly initialized. However, in real-world programming, you might encounter situations where a Set variable is null. Attempting to call methods like isEmpty() or size() on a null object will result in a NullPointerException, which is a common error in Java. It's important to handle these cases gracefully.

  1. Open the SetCheck.java file in your ~/project directory in the WebIDE editor.

  2. Modify the main method to demonstrate how to handle a null set. Replace the existing main method with the following code:

    import java.util.HashSet;
    import java.util.Set;
    
    public class SetCheck {
    
        public static void main(String[] args) {
            // Declare a Set variable but initialize it to null
            Set<String> colors = null;
    
            // Attempting to call isEmpty() or size() here would cause a NullPointerException
            // System.out.println("Is the colors set empty? " + colors.isEmpty()); // This would crash!
    
            // To safely check if a set is null or empty, we first check for null
            if (colors == null) {
                System.out.println("The colors set is null.");
            } else {
                // If it's not null, we can safely check if it's empty
                if (colors.isEmpty()) {
                    System.out.println("The colors set is empty.");
                } else {
                    System.out.println("The colors set is not empty and has " + colors.size() + " elements.");
                }
            }
    
            // Now, let's initialize the set and add elements
            colors = new HashSet<>();
            colors.add("Red");
            colors.add("Blue");
    
            // Check again after initialization and adding elements
            if (colors == null) {
                System.out.println("The colors set is null.");
            } else {
                if (colors.isEmpty()) {
                    System.out.println("The colors set is empty.");
                } else {
                    System.out.println("The colors set is not empty and has " + colors.size() + " elements.");
                }
            }
        }
    }

    In this updated code:

    • Set<String> colors = null;: We declare a Set variable colors but explicitly set it to null.
    • We commented out the line that would cause a NullPointerException.
    • if (colors == null): This is the crucial check. Before calling any methods on the colors variable, we first check if it is null.
    • If colors is not null, we then proceed to check if it's empty using colors.isEmpty() or get its size using colors.size().
    • We then initialize colors with a new HashSet and add elements to show the different output when the set is not null and not empty.
  3. Save the SetCheck.java file.

  4. Compile the program in the Terminal:

    javac SetCheck.java
  5. Run the program:

    java SetCheck

    You should see output similar to this:

    The colors set is null.
    The colors set is not empty and has 2 elements.

    This demonstrates how to safely handle potential null values for a Set variable before attempting to access its methods. Always check for null first when dealing with object references that might not be initialized.

Summary

In this lab, we learned how to check if a Set in Java is empty. We started by using the isEmpty() method, which is the standard and most efficient way to perform this check. We created a HashSet, checked its empty status before and after adding elements, and observed the boolean output of isEmpty(). This demonstrated the basic usage of isEmpty() for determining if a set contains any elements.