Java ProgramsCollectionsTreeSet Example

TreeSet Example in Java

intermediate·  Collections  ·  Set

Problem

A TreeSet keeps its elements in sorted order at all times, so iterating it always produces them from smallest to largest — regardless of the order they were added in.

Add several integers to a TreeSet in no particular order, then iterate over it.

Input
add(40), add(10), add(30), add(20)
Output
10 20 30 40

Java Program

Java
import java.util.Set; import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { Set<Integer> numbers = new TreeSet<>(); numbers.add(40); numbers.add(10); numbers.add(30); numbers.add(20); for (int n : numbers) { // always visits elements in sorted order System.out.println(n); } } }

Output

10 20 30 40

Core Logic

Every add() call inserts the new value into its correct sorted position immediately, so the set is always fully sorted and a plain for-each loop is enough to print the elements in order.

How It Works
  1. 1add(40), add(10), add(30), add(20) insert four values in a deliberately scrambled order.
  2. 2TreeSet stores elements in a self-balancing tree structure, ordered by their natural ordering — for Integer, that's ascending numeric order.
  3. 3There's no separate sort step — the tree is kept sorted as each element is inserted, not sorted afterward.
  4. 4The for-each loop simply walks the tree in order, printing 10, 20, 30, 40.
Even though 40 was added first, the loop prints it last — the insertion order has no effect on the iteration order at all.
💡

Key Point: Unlike HashSet, whose iteration order is unpredictable, TreeSet's iteration order is always the sorted order — that guarantee is the entire reason to choose it over a HashSet.

Complexity
Time Complexity: O(log n)Space Complexity: O(n)

Why: TreeSet is backed by a red-black tree, so add() and contains() both take O(log n) to find the correct position, while iterating every element in order takes O(n) total.

Key Concepts

TreeSetsorted setnatural ordering

Related Programs