Java TreeSet remove() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, remove(o) removes the element matching o from the TreeSet and returns true if the set contained it, or false if nothing matched.

Unlike ArrayList, a TreeSet has no numeric indexes, so set.remove(14) always removes the number 14 itself. It finds the node in O(log n) time using the tree's ordering.

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

Pass the object to remove; check the boolean result to see whether it existed.

Java
TreeSet<Integer> seats = new TreeSet<>(Arrays.asList(10, 14, 22));
boolean gone = seats.remove(14);    // true: [10, 22]
boolean miss = seats.remove(99);    // false: still [10, 22]
CallWhat it does
set.remove(o)Deletes the matching element; returns true if removed.
set.remove(14)Removes the value 14 (no index confusion).
set.pollFirst()Removes and returns the smallest element.
it.remove()Safely deletes the current item while iterating.

With a custom Comparator, remove(o) deletes any element for which compare(o, elem) == 0, even if equals() would say false.

Library declarations
Java
// java.util.TreeSet<E>
public boolean remove(Object o)

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

Parameters

ParameterDescription
o (Object)The object to remove. Must be comparable with the elements in the set.

Return Value

Return ValueDescription
trueA matching element was found and removed.
falseNo matching element existed in the set.

Compare with Similar Methods

Other ways to delete elements from a TreeSet:

MethodHow it differs
pollFirst()Removes and returns the smallest element without knowing its value.
pollLast()Removes and returns the largest element.
clear()Removes every element at once.
ArrayList.remove(o)Uses equals() and has an int index overload trap.

Java Examples

Example 1 — Cancel an Event Seat and Check Whether It Was Booked

Remove an existing seat number from sorted reservations, then attempt to remove a free seat.

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

public class TreeSetRemoveSeat {
    public static void main(String[] args) {
        TreeSet<Integer> booked = new TreeSet<>(Arrays.asList(14, 7, 21, 3));
        System.out.println("booked: " + booked);

        boolean canceled = booked.remove(14);
        boolean unknown = booked.remove(99);
        System.out.println("canceled 14? " + canceled);
        System.out.println("canceled 99? " + unknown);
        System.out.println("remaining: " + booked);
    }
}

How It Works

  1. No index trap. Calling remove(14) targets the value 14 directly, unlike a list where numbers act as indexes.
  2. Boolean feedback. Removing 14 succeeds and returns true, while missing seat 99 returns false without error.
  3. Tree stays balanced and sorted. Removing an inner node rebalances the red-black tree, leaving [3, 7, 21].

Example 2 — Remove Using a Case-Insensitive Comparator

Store mixed-case names with String.CASE_INSENSITIVE_ORDER and remove "Alice" using all caps.

Java
import java.util.TreeSet;

public class TreeSetRemoveComparator {
    public static void main(String[] args) {
        TreeSet<String> guests = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        guests.add("Alice");
        guests.add("bob");
        guests.add("Carol");

        boolean removed = guests.remove("ALICE");
        System.out.println("removed ALICE? " + removed);
        System.out.println("guests left: " + guests);
    }
}

How It Works

  1. Comparator decides equality. TreeSet finds "Alice" when asked for "ALICE" because CASE_INSENSITIVE_ORDER.compare returns 0.
  2. Case mismatch still deletes. Even though "Alice".equals("ALICE") is false, the entry is deleted and remove() returns true.
  3. Remaining order preserved. bob and Carol remain sorted alphabetically ignoring case.

Example 3 — Wrong Type Errors and Safe Loop Removal

See ClassCastException on an incompatible key, then safely remove elements above a threshold using iterator().

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

public class TreeSetRemoveErrors {
    public static void main(String[] args) {
        TreeSet<Integer> levels = new TreeSet<>(Arrays.asList(10, 25, 40, 55));

        try {
            levels.remove("high");
        } catch (ClassCastException e) {
            System.out.println("wrong type: " + e.getClass().getSimpleName());
        }

        Iterator<Integer> it = levels.iterator();
        while (it.hasNext()) {
            if (it.next() > 30) {
                it.remove();
            }
        }
        System.out.println("after iterator remove: " + levels);
    }
}

How It Works

  1. Runtime comparison check. Because remove(Object) accepts any object, passing "high" compiles but throws ClassCastException against Integer elements.
  2. Avoid direct remove in loops. Calling levels.remove() inside a for-each loop triggers ConcurrentModificationException.
  3. Iterator removal works cleanly. it.remove() deletes 40 and 55 while keeping the iterator synchronized with the tree.

Frequently Asked Questions

true if a matching element was found and removed, or false if the element was not in the set.
It removes the value 1. Sets do not have positional indexes like ArrayList does.
Because remove(Object) compares the argument against elements in the tree. Passing a String to a non-empty TreeSet of Integers fails when Java compares them.
Use an explicit Iterator and call it.remove(), use set.removeIf(condition), or clear a range view such as set.headSet(limit).clear().
Yes. TreeSet always uses its Comparator (or natural order) rather than equals() to match the element being removed.

Next: size()

Count how many unique elements are stored in the set.

size() 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.

7 people found this page helpful