TreeSet Example in Java
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.
Java Program
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
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.
- 1
add(40),add(10),add(30),add(20)insert four values in a deliberately scrambled order. - 2TreeSet stores elements in a self-balancing tree structure, ordered by their natural ordering — for
Integer, that's ascending numeric order. - 3There's no separate sort step — the tree is kept sorted as each element is inserted, not sorted afterward.
- 4The for-each loop simply walks the tree in order, printing
10, 20, 30, 40.
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.
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.