<code>TreeSet</code> in Java β€” Sorted Set

TreeSet is the sorted cousin of HashSet. Elements are stored in natural order or according to a Comparator. All main operations are O(log n), the same as TreeMap (the set is literally a TreeMap internally).

Basics

var names = new TreeSet<String>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
names.forEach(System.out::println);  // Alice, Bob, Charlie β€” sorted

Navigation

var s = new TreeSet<>(Set.of(10, 20, 30, 40));

s.first();                  // 10
s.last();                   // 40
s.floor(25);                // 20 β€” largest ≀
s.ceiling(25);              // 30 β€” smallest β‰₯
s.headSet(30);              // [10, 20] β€” strictly <
s.tailSet(20);              // [20, 30, 40] β€” from β‰₯
s.subSet(15, 35);           // [20, 30] β€” half-open

Reverse order

var desc = new TreeSet<Integer>(Comparator.reverseOrder());
desc.addAll(List.of(3, 1, 4, 1, 5));
// iterates 5, 4, 3, 1

When TreeSet wins

  • You frequently need "the smallest/largest element" or "everything in this range".
  • You need to iterate in sorted order repeatedly (a sort-on-demand HashSet is wasteful).

For simple deduplication with no ordering need, HashSet is faster.

Common mistakes

  • Non-Comparable elements β€” ClassCastException. Supply a Comparator.
  • Mutable elements that change their ordering key β€” the tree becomes inconsistent.
  • Custom Comparator inconsistent with equals β€” two elements that compare equal-by-comparator but !.equals() cause duplicates visually equal but distinct.

Related

Pillar: Java collections. Siblings: TreeMap, HashSet.