Java TreeSet

Beginner
9 min read
Updated: Nov 2026
3 examples
java.util.TreeSet

Definition and Usage

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

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.

Natural Ordering, Comparator, and Duplicate Rules

Every element in a TreeSet must be comparable:

RuleWhat happens
Natural orderingElements must implement Comparable (such as Integer or String). Adding an uncomparable object throws ClassCastException.
Custom ComparatorPass a Comparator to the constructor (like String.CASE_INSENSITIVE_ORDER). comparator() returns it, or null for natural order.
Comparator decides duplicatesEquality is tested with compareTo / compare == 0, not equals(). With a case-insensitive comparator, adding "java" after "Java" returns false and keeps "Java".
null elementsWith natural ordering, adding null throws NullPointerException. A null-safe comparator like Comparator.nullsFirst(...) allows it.

TreeSet vs HashSet vs LinkedHashSet

All three implement Set and reject duplicates, but differ in order, speed, and null support:

ClassOrderCost (add / contains)Allows null?
TreeSetSorted (natural or Comparator)O(log n)No (by default)
HashSetNo guaranteed orderO(1) on averageYes (one null)
LinkedHashSetInsertion orderO(1) on averageYes (one null)

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.

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

public class TreeSetHubLeaderboard {
    public static void main(String[] args) {
        NavigableSet<Integer> scores = new TreeSet<>(Arrays.asList(75, 92, 60, 75, 88, 92));

        System.out.println("sorted unique: " + scores);
        System.out.println("lowest: " + scores.first() + ", highest: " + scores.last());
        System.out.println("floor(80): " + scores.floor(80) + ", ceiling(80): " + scores.ceiling(80));
        System.out.println("add 88 again: " + scores.add(88));
    }
}

How It Works

  1. One step does both. Passing the list to new TreeSet<>(...) drops the repeated 75 and 92 while sorting the rest into [60, 75, 88, 92].
  2. Direct end access. first() and last() return 60 and 92 from the tree's edges without scanning.
  3. Nearest neighbours. 80 is missing, so floor(80) drops to 75 and ceiling(80) steps up to 88.
  4. Duplicate rejected. Calling add(88) sees 88 already in the tree and returns false.

Example 2 — Custom Comparator: Case-Insensitive Rules and the Duplicate Trap

See how String.CASE_INSENSITIVE_ORDER sorts names alphabetically and treats different-case spellings as duplicates.

Java
import java.util.TreeSet;

public class TreeSetHubComparator {
    public static void main(String[] args) {
        TreeSet<String> natural = new TreeSet<>();
        natural.add("banana");
        natural.add("Apple");
        System.out.println("natural order: " + natural);

        TreeSet<String> ci = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        System.out.println("add Java: " + ci.add("Java"));
        System.out.println("add java: " + ci.add("java"));
        ci.add("alpha");
        System.out.println("case-insensitive: " + ci + ", contains JAVA? " + ci.contains("JAVA"));
    }
}

How It Works

  1. UTF-16 natural order. Uppercase letters come before lowercase letters in Unicode, so "Apple" prints before "banana".
  2. Comparator equals zero. Because CASE_INSENSITIVE_ORDER compares "java" and "Java" as 0, the second insert is treated as a duplicate.
  3. First element kept. "Java" stays in the set while "java" is ignored and add returns false.
  4. Lookup matches comparator. contains("JAVA") also uses the comparator, so it returns true.

Example 3 — Live Range Views and Why Natural Ordering Rejects null

Slice a live subSet, write through it, then catch the NullPointerException when adding null.

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

public class TreeSetHubViewsNull {
    public static void main(String[] args) {
        NavigableSet<Integer> slots = new TreeSet<>(Arrays.asList(900, 1000, 1130, 1400));
        NavigableSet<Integer> morning = slots.headSet(1200, false);
        System.out.println("morning slots: " + morning);

        morning.add(1030);
        System.out.println("all slots: " + slots);
        System.out.println("reversed: " + slots.descendingSet());

        try {
            slots.add(null);
        } catch (NullPointerException e) {
            System.out.println("add(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Backed range view. headSet(1200, false) views all time slots strictly below 1200 without copying them.
  2. Write-through update. Adding 1030 to morning inserts 1030 directly into the original slots tree.
  3. Instant reverse view. descendingSet() flips the view from high to low without building a second tree.
  4. Null refused. Natural ordering compares elements with compareTo, so adding null throws NullPointerException.

Next: Java TreeSet Methods by Group

Full list with short descriptions: Java TreeSet Methods index.

Frequently Asked Questions

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.

Browse every TreeSet method

Open the methods index for categorized guides with examples and FAQs.

TreeSet Methods Index →

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.

9 people found this page helpful