← Back to Core Java Course | Chapter 11: Collections | Lesson 12 of 17

Java TreeSet

TreeSet is a Set implementation that stores its elements in a self-balancing tree, keeping them automatically sorted in ascending order at all times.
Syntax
java
TreeSet<Type> set = new TreeSet<>();
set.add(item);  // sorted order
set.first();

Introduction to TreeSet

TreeSet is an implementation of the Set interface that stores its elements in a red-black tree, a self-balancing binary search tree, which keeps every element automatically arranged in sorted order at all times.

Example: Introduction to TreeSet

java
import java.util.TreeSet;
public class Main {
	public static void main(String[] args) {
		TreeSet<Integer> set = new TreeSet<>(); // red-black tree
		set.add(5);
		set.add(1);
		System.out.println(set);
	}
}

Automatic Sorting

Elements added to a TreeSet are sorted according to their natural ordering by default -- numbers sort numerically and strings sort alphabetically -- regardless of the order they happened to be inserted in.

Example: Automatic Sorting

java
import java.util.TreeSet;
public class Main {
	public static void main(String[] args) {
		TreeSet<Integer> set = new TreeSet<>();
		set.add(3);
		set.add(1);
		set.add(2);
		System.out.println(set); // sorted: 1, 2, 3
	}
}

Adding and Removing Elements

TreeSet supports the same add and remove operations as any other Set, but every insertion or removal also re-balances the underlying tree to keep the sorted order intact, and duplicate values are still rejected.

Example: Adding and Removing Elements

java
import java.util.TreeSet;
public class Main {
	public static void main(String[] args) {
		TreeSet<Integer> set = new TreeSet<>();
		set.add(5);
		set.add(5); // duplicate ignored
		set.remove(5);
		System.out.println(set);
	}
}

Navigation Methods

TreeSet adds navigation methods beyond a plain Set, like first, last, higher, and lower, which take advantage of the guaranteed sort order to efficiently find the smallest, largest, or nearest elements relative to a given value.

Example: Navigation Methods

java
// Import java.util.TreeSet so it can be used by its short name
import java.util.TreeSet;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new TreeSet object and store it in set
		TreeSet<Integer> set = new TreeSet<>();
		set.add(1); set.add(5); set.add(10);
		// Print a line to the console
		System.out.println(set.first());
		// Print a line to the console
		System.out.println(set.last());
		System.out.println(set.higher(5));
	}
}

Custom Sort Order with Comparator

Passing a Comparator to a TreeSet's constructor overrides the default natural ordering, letting elements be sorted by any custom rule, such as reverse order or by a computed property like string length instead of alphabetical order.

Example: Custom Sort Order with Comparator

java
import java.util.TreeSet;
import java.util.Collections;
public class Main {
	public static void main(String[] args) {
		TreeSet<Integer> set = new TreeSet<>(Collections.reverseOrder());
		set.add(1);
		set.add(5);
		System.out.println(set); // reverse sorted
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Adding null, which throws NullPointerException.
  2. Adding objects that are not comparable, which throws ClassCastException.
  3. Expecting duplicates to be stored, when they are ignored.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.