Java Set isEmpty() example

In this guide, you will learn about the Set isEmpty() method in Java programming and how to use it with an example.

1. Set isEmpty() Method Overview

Definition:

The isEmpty() method of the Java Set interface returns true if the set contains no elements.

Syntax:

boolean isSetEmpty = set.isEmpty();

Parameters:

None.

Key Points:

- The method returns true if this set contains no elements.

- It's a more readable alternative to checking if set.size() == 0.

- Useful in scenarios where you want to take some action only if the set is empty.

2. Set isEmpty() Method Example

import java.util.HashSet;
import java.util.Set;

public class SetIsEmptyExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();

        // Checking if the set is empty initially
        System.out.println("Is the set empty? : " + fruits.isEmpty());  // true

        // Adding an element and checking again
        fruits.add("Apple");
        System.out.println("Is the set empty after adding an element? : " + fruits.isEmpty());  // false

        // Clearing the set and checking again
        fruits.clear();
        System.out.println("Is the set empty after clearing? : " + fruits.isEmpty());  // true
    }
}

Output:

Is the set empty? : true
Is the set empty after adding an element? : false
Is the set empty after clearing? : true

Explanation:

In this example:

1. We create a HashSet of fruits.

2. Initially, the set is empty, and isEmpty() returns true.

3. After adding "Apple" to the set, isEmpty() returns false as the set now contains an element.

4. Finally, we clear the set using the clear() method. isEmpty() then again returns true since the set is empty.

The isEmpty() method is a straightforward way to check for the absence of elements in a set without having to inspect its size or content directly.

Related Java Set interface methods

Java Set add() example
Java Set contains() example
Java Set isEmpty() example
Java Set remove() example
Java Set size() example

Comments