TreeSet in Java

TreeSet stores unique elements in sorted order using a red-black tree, providing O(log n) add, remove, and contains operations.

TreeSet<E> is a NavigableSet implementation backed by a TreeMap. Every element is kept in ascending sorted order — either the element's natural ordering (via Comparable) or a custom Comparator supplied at construction time. All core operations run in O(log n) time because the underlying structure is a self-balancing red-black tree.

How TreeSet Works Internally

Internally, TreeSet delegates to a TreeMap<E, Object>. Each element becomes a key in that map, with a shared dummy value. The TreeMap maintains a red-black tree: a balanced binary search tree that guarantees O(log n) height. On every add, remove, or contains, the tree is traversed using the element's ordering, which is why the ordering must be consistent and non-null.

Operation Time complexity
add O(log n)
remove O(log n)
contains O(log n)
first/last O(log n)
headSet/tailSet/subSet O(log n) to establish view
Iteration O(n)

Key characteristics:

  • No duplicate elements.
  • Elements are always in sorted order.
  • null keys are not allowed with natural ordering (throws NullPointerException). A Comparator that explicitly handles null can be used, but this is uncommon.
  • Not thread-safe.
  • Provides rich navigation methods: floor, ceiling, lower, higher, headSet, tailSet, subSet, descendingSet.

Examples

Natural ordering

import java.util.TreeSet;
import java.util.NavigableSet;

public class TreeSetNatural {
    public static void main(String[] args) {
        NavigableSet<Integer> primes = new TreeSet<>();
        primes.add(7);
        primes.add(2);
        primes.add(13);
        primes.add(5);
        primes.add(2);  // duplicate — ignored

        System.out.println(primes);          // [2, 5, 7, 13]
        System.out.println(primes.first());  // 2
        System.out.println(primes.last());   // 13
        System.out.println(primes.floor(6)); // 5  (greatest element ≤ 6)
        System.out.println(primes.ceiling(6)); // 7 (smallest element ≥ 6)

        // Range view — elements from 3 (inclusive) to 10 (exclusive)
        System.out.println(primes.subSet(3, 10)); // [5, 7]
    }
}

Custom ordering with Comparator

import java.util.Comparator;
import java.util.TreeSet;
import java.util.Set;

public class TreeSetCustomOrder {
    record Product(String name, double price) {}

    public static void main(String[] args) {
        // Sort products by price ascending, then by name for ties
        Set<Product> catalog = new TreeSet<>(
            Comparator.comparingDouble(Product::price)
                      .thenComparing(Product::name)
        );

        catalog.add(new Product("Widget", 9.99));
        catalog.add(new Product("Gadget", 24.99));
        catalog.add(new Product("Gizmo", 9.99));

        for (Product p : catalog) {
            System.out.printf("%-10s $%.2f%n", p.name(), p.price());
        }
        // Output (sorted by price, then name):
        // Gizmo      $9.99
        // Widget     $9.99
        // Gadget     $24.99
    }
}

Common Mistakes

  1. Inserting null with natural ordering. Adding null to a TreeSet that uses natural ordering throws NullPointerException because the tree must call compareTo(null). Unlike HashSet, there is no bucket-0 slot for null.

  2. Inconsistent compareTo vs equals. TreeSet uses its ordering to determine equality — two elements are considered duplicates if compareTo returns 0, regardless of equals. If compareTo is inconsistent with equals (e.g., a.equals(b) is true but a.compareTo(b) != 0), the set will contain both, violating the Set contract.

  3. Subtraction-based comparators. Writing Comparator<Integer> c = (a, b) -> a - b is dangerous: for large values, Integer.MIN_VALUE - 1 overflows to Integer.MAX_VALUE, reversing the order. Use Integer.compare(a, b) or Comparator.comparingInt(...) instead.

  4. Mutating elements after insertion. If you change a field that the ordering depends on after an element is in the TreeSet, the tree invariant breaks silently. The element may become unreachable.

  5. Using TreeSet when HashSet suffices. If you only need uniqueness and do not need ordering, HashSet is faster (O(1) vs O(log n)). Reach for TreeSet specifically when sorted access or range queries are required.

Best Practices

  • Declare variables as NavigableSet<E> or SortedSet<E> to make the sorted-access API visible.
  • Always supply a Comparator that is consistent with equals unless element types implement Comparable correctly.
  • Use Comparator.comparing + thenComparing chains instead of subtraction-based comparators.
  • Use headSet, tailSet, and subSet for efficient range operations — they return live views backed by the same tree.
  • Use TreeSet with a Comparator when you want to store custom objects in a sorted set without modifying those objects.

Interview Questions

1. What data structure backs TreeSet?

TreeSet is backed by a TreeMap, which is implemented as a red-black tree. A red-black tree is a self-balancing binary search tree that guarantees O(log n) height, ensuring O(log n) worst-case time for all navigation and modification operations.

2. Why does TreeSet not allow null elements with natural ordering?

During insertion, TreeSet calls compareTo on the new element relative to existing elements. null does not have a compareTo method, so the call throws NullPointerException. A Comparator that explicitly handles null (e.g., Comparator.nullsFirst(...)) can work around this, but it is rarely recommended.

3. What is the difference between TreeSet and HashSet?

HashSet provides O(1) average operations with no ordering guarantee. TreeSet provides O(log n) operations and keeps elements in sorted order. TreeSet supports navigation methods (floor, ceiling, range views) that HashSet cannot. Use HashSet for raw performance; use TreeSet when sorted access matters.

4. What does it mean for compareTo to be inconsistent with equals?

compareTo returning 0 means the TreeSet considers two elements equal (duplicates). If equals disagrees (returns false), the Set contract is violated: the set should store all elements for which equals is false, but the tree discards one of them. Always ensure compareTo returns 0 exactly when equals returns true.

5. How do range views work in TreeSet?

subSet(from, to), headSet(to), and tailSet(from) return NavigableSet views backed by the same tree. They are live views — changes to the original set are reflected in the view and vice versa. Range views also enforce their own bounds: attempting to insert an out-of-range element into a subSet view throws IllegalArgumentException.

6. How does TreeSet handle a custom sort order?

Pass a Comparator<E> to the constructor: new TreeSet<>(myComparator). The tree uses this comparator for all insertions, lookups, and ordering decisions instead of the natural ordering. The comparator must be consistent with equals to satisfy the Set contract.

7. What navigation methods does TreeSet provide that HashSet does not?

TreeSet provides first(), last(), floor(e) (greatest ≤ e), ceiling(e) (smallest ≥ e), lower(e) (greatest < e), higher(e) (smallest > e), pollFirst(), pollLast(), descendingSet(), and range-view methods (headSet, tailSet, subSet). None of these are available on HashSet.

Summary

  • TreeSet stores unique elements in sorted (natural or custom-comparator) order using a red-black tree.
  • All core operations run in O(log n); null elements are not supported with natural ordering.
  • It is backed by TreeMap and exposes the full NavigableSet API for range and navigation queries.
  • The Comparator or compareTo ordering must be consistent with equals to satisfy the Set contract.
  • Use HashSet for raw speed; use TreeSet when sorted order or range queries are needed.

Continue Learning

Previous: LinkedHashSet | Next: Map

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.