TreeSet
A set that keeps its elements in sorted order.
Available since: Java 1.2
Syntax
public class TreeSet<E> implements NavigableSet<E>Examples
Elements are always sorted:
void main() {
Set<Integer> scores = new TreeSet<>(List.of(42, 7, 19, 7, 88));
IO.println(scores);
}Output:
[7, 19, 42, 88]Navigation: nearest values and ranges:
void main() {
TreeSet<Integer> set = new TreeSet<>(List.of(10, 20, 30, 40));
IO.println(set.first() + " " + set.last());
IO.println(set.ceiling(25));
IO.println(set.floor(25));
IO.println(set.headSet(30));
}Output:
10 40
30
20
[10, 20]Notes
Operations run in logarithmic time — slower than HashSet, but the order is always sorted. Elements must implement Comparable, or a Comparator is passed to the constructor: new TreeSet<>(Comparator.reverseOrder()). Elements the comparator considers equal count as duplicates.
See also
- HashSet — A set without duplicates backed by a hash table; order is not guaranteed.
- LinkedHashSet — A set that remembers the insertion order of elements.
- TreeMap — A map whose keys are always sorted.
- Comparator.comparing() — Creates a comparator that compares objects by one key.
Related recipes
In the tutorial
- Sets: Set — Sets in Java: HashSet without duplicates, LinkedHashSet and TreeSet with ordering, union and intersection of sets.