Home Java TreeSet Methods isEmpty() Java TreeSet isEmpty() Method 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.
TreeSet<String> pending = new TreeSet<>();
if (pending.isEmpty()) {
System.out.println("Nothing to process");
} Call What 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.util.TreeSet<E>
public boolean isEmpty()
// Declared in Set<E> and Collection<E> Parameters Parameter Description None isEmpty() takes no parameters.
Return Value Return Value Description trueThe set contains zero elements. falseThe set contains one or more elements.
Important
isEmpty() checks the set at the moment of the call, not whether the variable itself is null: calling isEmpty() on a null reference still throws NullPointerException. On an empty TreeSet, calling first() or last() throws NoSuchElementException.
Compare with Similar Methods Checking size and guarding empty sets:
Method How 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 1. Guard first and last 2. Drain loop 3. Range emptiness check 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.
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);
}
} queue is empty
range: 15 to 40 How It Works Empty check prevents crash. Calling first() directly on an empty set throws NoSuchElementException, so isEmpty() skips it.Populated state detected. Once 40 and 15 are added, isEmpty() returns false.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().
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());
}
} initially empty? false
handled: E01
handled: E02
handled: E03
after loop empty? true How It Works Starts non-empty. Three alert codes sit inside the tree, so isEmpty() returns false.Sorted drain loop. Each iteration pops the lowest code (E01, E02, E03) until none remain.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.
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);
}
} any freezing (-10..0)? false
any mild (15..25)? true How It Works Empty range view. None of 12, 18, 22, 27 sit between -10 and 0, so that subSet is empty and !isEmpty() is false.Non-empty range view. 18 and 22 fall inside 15..25, so isEmpty() stops after checking the first match and returns false.Faster than counting. Checking !subSet(...).isEmpty() avoids counting all items in the slice.Frequently Asked Questions What does TreeSet isEmpty() return? true if the TreeSet contains zero elements, or false if it has at least one element.
Should I use set.isEmpty() or set.size() == 0? Use set.isEmpty(). It reads more clearly and can be faster on subSet, headSet, and tailSet range views.
Does isEmpty() check whether the variable is null? No. If the TreeSet variable itself is null, calling set.isEmpty() throws NullPointerException.
How does isEmpty() behave on a subSet()? It returns true when no element from the backing TreeSet falls within the view bounds, even if the backing set itself is non-empty.
What happens if I call clear() and then isEmpty()? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion