Iterating TreeSet: Always Sorted Order
You'll learn: How TreeSet guarantees that iteration always returns elements in sorted order, unlike HashSet's unpredictable sequence.
The Guarantee of Sorted Iteration
When you iterate over a TreeSet, you always get elements in their sorted order. This happens automatically because TreeSet maintains its underlying red-black tree structure in sorted order at all times. Every element is positioned according to its natural ordering (or custom comparator), so when you traverse the tree, you traverse it in sequence.
This is fundamentally different from HashSet, where iteration order appears random and depends on hash codes and internal bucket positions.
How It Works
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(50);
numbers.add(20);
numbers.add(80);
numbers.add(10);
// Iteration always produces: 10, 20, 50, 80
for (Integer num : numbers) {
System.out.println(num);
}
No matter what order you added elements, iteration produces them in ascending order.
String Example
TreeSet<String> names = new TreeSet<>();
names.add("Charlie");
names.add("Alice");
names.add("Diana");
names.add("Bob");
// Iteration always produces: Alice, Bob, Charlie, Diana
for (String name : names) {
System.out.println(name);
}
The Underlying Mechanism
The sorted iteration comes from an in-order traversal of the red-black tree: left subtree → current node → right subtree. This traversal pattern naturally visits nodes in ascending order, giving you sorted iteration "for free" once the tree is constructed.
Key Takeaway: TreeSet iteration always produces elements in sorted order, making it ideal when you need predictable, sorted traversal without explicit sorting after collection.