Java TreeSet isEmpty() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, isEmpty() returns true when the TreeSet holds zero elements and false when at least one element is present.

Checking !set.isEmpty() before calling first() or last() prevents NoSuchElementException, and calling isEmpty() on a range view is also cleaner and faster than checking size() == 0.

An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.

Syntax

Call isEmpty() before reading endpoints or inside a loop condition.

Java
TreeSet<String> pending = new TreeSet<>();
if (pending.isEmpty()) {
    System.out.println("Nothing to process");
}
CallWhat it does
set.isEmpty()true when the set has 0 elements.
!set.isEmpty()true when at least 1 element is present.
while (!set.isEmpty())Runs until every element is polled or removed.
set.subSet(a, b).isEmpty()Checks whether any element falls inside a range.

On a range view (subSet, headSet, tailSet), isEmpty() only checks whether a single element exists in the range instead of counting every matching element like size() == 0 may do.

Library declarations
Java
// java.util.TreeSet<E>
public boolean isEmpty()

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
NoneisEmpty() takes no parameters.

Return Value

Return ValueDescription
trueThe set contains zero elements.
falseThe set contains one or more elements.

Compare with Similar Methods

Checking size and guarding empty sets:

MethodHow it differs
size()Returns the exact element count instead of just empty vs non-empty.
first()Throws NoSuchElementException when isEmpty() is true.
pollFirst()Returns null when empty instead of throwing.
clear()Empties the set so isEmpty() becomes true.

Java Examples

Example 1 — Guard first() and last() With isEmpty()

Safely report the range of scheduled task IDs when the set starts empty and after adding IDs.

Java
import java.util.TreeSet;

public class TreeSetIsEmptyGuard {
    static void printSummary(TreeSet<Integer> tasks) {
        if (tasks.isEmpty()) {
            System.out.println("queue is empty");
        } else {
            System.out.println("range: " + tasks.first() + " to " + tasks.last());
        }
    }

    public static void main(String[] args) {
        TreeSet<Integer> tasks = new TreeSet<>();
        printSummary(tasks);

        tasks.add(40);
        tasks.add(15);
        printSummary(tasks);
    }
}

How It Works

  1. Empty check prevents crash. Calling first() directly on an empty set throws NoSuchElementException, so isEmpty() skips it.
  2. Populated state detected. Once 40 and 15 are added, isEmpty() returns false.
  3. Safe endpoint read. Entering the else branch prints 15 to 40 safely.

Example 2 — Drain Priority Alerts Until isEmpty() Becomes true

Process alert codes in sorted order using while (!alerts.isEmpty()) and pollFirst().

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetIsEmptyDrain {
    public static void main(String[] args) {
        TreeSet<String> alerts = new TreeSet<>(Arrays.asList("E03", "E01", "E02"));
        System.out.println("initially empty? " + alerts.isEmpty());

        while (!alerts.isEmpty()) {
            System.out.println("handled: " + alerts.pollFirst());
        }
        System.out.println("after loop empty? " + alerts.isEmpty());
    }
}

How It Works

  1. Starts non-empty. Three alert codes sit inside the tree, so isEmpty() returns false.
  2. Sorted drain loop. Each iteration pops the lowest code (E01, E02, E03) until none remain.
  3. Loop terminates cleanly. Once E03 is removed, !alerts.isEmpty() evaluates to false and stops.

Example 3 — Check Whether Any Element Falls in a subSet() Range

Use isEmpty() on a subSet() view to test if any temperatures lie in a freezing band.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetIsEmptyRange {
    public static void main(String[] args) {
        TreeSet<Integer> temps = new TreeSet<>(Arrays.asList(12, 18, 22, 27));

        boolean anyFreezing = !temps.subSet(-10, true, 0, true).isEmpty();
        boolean anyMild = !temps.subSet(15, true, 25, true).isEmpty();

        System.out.println("any freezing (-10..0)? " + anyFreezing);
        System.out.println("any mild (15..25)?     " + anyMild);
    }
}

How It Works

  1. Empty range view. None of 12, 18, 22, 27 sit between -10 and 0, so that subSet is empty and !isEmpty() is false.
  2. Non-empty range view. 18 and 22 fall inside 15..25, so isEmpty() stops after checking the first match and returns false.
  3. Faster than counting. Checking !subSet(...).isEmpty() avoids counting all items in the slice.

Frequently Asked Questions

true if the TreeSet contains zero elements, or false if it has at least one element.
Use set.isEmpty(). It reads more clearly and can be faster on subSet, headSet, and tailSet range views.
No. If the TreeSet variable itself is null, calling set.isEmpty() throws NullPointerException.
It returns true when no element from the backing TreeSet falls within the view bounds, even if the backing set itself is non-empty.
clear() removes all elements, so isEmpty() immediately returns true.

Next: iterator()

Walk the elements in ascending order and remove safely during the loop.

iterator() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful