In Java, TreeSet (in java.util, since Java 1.2) stores unique elements in sorted order. Inside, it is backed by a TreeMap (a self-balancing red-black tree), so add(), remove(), and contains() run in O(log n) time regardless of insertion order.
It implements NavigableSet (added in Java 6), SortedSet, Set, Cloneable, and Serializable. Java 21 also adds SequencedSet methods such as getFirst() and reversed(), while this guide focuses on Java 8+ methods. Browse every guide in the TreeSet Methods index.
Not thread-safe and no null by default.
TreeSet rejects null with NullPointerException under natural ordering, and is not thread-safe: wrap it with Collections.synchronizedSortedSet(...) (and lock around iterations) or use ConcurrentSkipListSet. Iterators are fail-fast and throw ConcurrentModificationException if the set changes outside it.remove().
Syntax
Java Syntax
Import TreeSet and create one using natural ordering, a custom Comparator, or another collection:
Java
import java.util.Arrays;
import java.util.Comparator;
import java.util.NavigableSet;
import java.util.TreeSet;
NavigableSet<Integer> ids = new TreeSet<>(); // natural order
NavigableSet<Integer> desc = new TreeSet<>(Comparator.reverseOrder()); // largest first
TreeSet<String> unique = new TreeSet<>(Arrays.asList("b", "a", "b")); // [a, b]
Numbers are autoboxed into Integer or Double. Java 9's Set.of(...) creates small unmodifiable unsorted sets; use new TreeSet<>() when you need sorted elements or updates.
Concept
Natural Ordering, Comparator, and Duplicate Rules
Every element in a TreeSet must be comparable:
Rule
What happens
Natural ordering
Elements must implement Comparable (such as Integer or String). Adding an uncomparable object throws ClassCastException.
Custom Comparator
Pass a Comparator to the constructor (like String.CASE_INSENSITIVE_ORDER). comparator() returns it, or null for natural order.
Comparator decides duplicates
Equality is tested with compareTo / compare == 0, not equals(). With a case-insensitive comparator, adding "java" after "Java" returns false and keeps "Java".
null elements
With natural ordering, adding null throws NullPointerException. A null-safe comparator like Comparator.nullsFirst(...) allows it.
Reference
Navigation Methods and Live Views
Because elements sit in a sorted tree, TreeSet can jump to nearest neighbours with floor(), ceiling(), lower(), and higher(), read or remove ends with first(), last(), pollFirst(), and pollLast(), and slice live backed ranges with subSet(), headSet(), tailSet(), and descendingSet(). Changes to a range or reversed view write straight back to the original TreeSet; adding outside a range view's bounds throws IllegalArgumentException.
Reference
TreeSet vs HashSet vs LinkedHashSet
All three implement Set and reject duplicates, but differ in order, speed, and null support:
Class
Order
Cost (add / contains)
Allows null?
TreeSet
Sorted (natural or Comparator)
O(log n)
No (by default)
HashSet
No guaranteed order
O(1) on average
Yes (one null)
LinkedHashSet
Insertion order
O(1) on average
Yes (one null)
Code
Java Examples
Example 1 — Remove Duplicates and Sort Scores Automatically
Feed duplicate scores into a TreeSet, inspect the sorted output, and query the ends and nearest neighbours.
TreeSet is a class in java.util that stores unique elements in sorted order inside a self-balancing red-black tree (backed by a TreeMap). Adding, removing, and checking membership take O(log n) time.
No by default. Because TreeSet must compare elements to sort them, adding null with natural ordering throws NullPointerException. Only a custom Comparator written to accept null (such as Comparator.nullsFirst) allows it.
It checks whether compareTo() or the Comparator returns 0, rather than calling equals(). With a case-insensitive comparator, "Java" and "java" compare as 0, so the second one is rejected.
HashSet keeps no guaranteed order and is O(1) on average; LinkedHashSet preserves insertion order; TreeSet keeps elements sorted (natural order or Comparator) in O(log n) time and adds range and neighbour methods like floor(), ceiling(), and subSet().
No. Wrap it with Collections.synchronizedSortedSet(...) or Collections.synchronizedNavigableSet(...) and synchronize manually while iterating, or use ConcurrentSkipListSet for concurrent access.