TreeSet
TreeSet is a set backed by a TreeMap. Elements stay sorted. Add, remove, and contains are O(log n). It offers range views like headSet and ceiling.
Detailed Explanation
When uniqueness and order both matter, HashSet cannot help: it has no order. TreeSet keeps elements in a red-black tree. Iteration is sorted. first, last, ceiling, floor, subSet, headSet, and tailSet answer range questions without scanning the whole set.
Ordering is Comparable or a constructor Comparator. The comparator must be consistent with equals for the Set contract: compare-to-zero means "already in the set". Two BigDecimal values that are numerically equal but have different scales (1.0 and 1.00) compare equal and are duplicates in a TreeSet, which surprises people who used equals in a HashSet (those two are not equals).
null is not allowed with natural order. The set is not thread-safe. ConcurrentSkipListSet is the concurrent sorted set.
You reach for TreeSet when you need sorted unique values and range queries: the next available id, all events before noon, a leaderboard of unique scores. You keep HashSet for membership only. You use LinkedHashSet for unique-plus-insertion-order. You sort a list once if the data is write-once and read-many without incremental updates.
The cost is O(log n) and comparator overhead. A HashSet is faster when you never need order. A sorted ArrayList plus Collections.binarySearch can be faster for a static set. Do not change fields that affect comparison after the element is in the set. subSet views are live: mutating them mutates the set.
NavigableSet methods (pollFirst, descendingSet) make the ends explicit. descendingSet is a view, not a copy.
A concrete case: you store unique booking dates and need "the next date on or after today". ceiling(today) is one tree walk. Building a HashSet and scanning it is linear. If you only ever ask "is this date booked?", a HashSet is enough and faster. Pick the set from the questions you ask, not from a habit of sorting everything.
Code Examples
import java.util.TreeSet;
public class Ranks {
public static void main(String[] args) {
TreeSet<Integer> scores = new TreeSet<>();
scores.add(10);
scores.add(3);
scores.add(7);
System.out.println(scores); // prints: [3, 7, 10]
System.out.println(scores.ceiling(6)); // prints: 7
System.out.println(scores.headSet(7)); // prints: [3]
}
}import java.util.Comparator;
import java.util.TreeSet;
public class Names {
public static void main(String[] args) {
TreeSet<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
names.add("Ana");
names.add("ana"); // compare == 0, so this is a duplicate
names.add("Bo");
System.out.println(names); // prints: [Ana, Bo]
}
}Common Gotchas
Comparator consistency with `equals`
`TreeSet` uses compare-to-zero, not `equals`, to decide uniqueness.
Incomparable elements throw `ClassCastException`
every element must work with the same comparator.
`subSet` is a live view
add an element in range through the view and the original set grows.
Not thread-safe
use `ConcurrentSkipListSet` when shared.