TreeSet (Sorted Set)
In short: A set that automatically keeps its elements in sorted order — every insert places the new element immediately at the correct spot.
In more detail: Internally usually implemented as a balanced search tree, which keeps inserting, searching, and removing significantly faster than a sorted list, but somewhat slower than an unsorted HashSet. The right choice when elements are always needed in ascending (or defined) order while iterating.
In Depth
set = new SortedSet()
set.add(5)
set.add(1)
set.add(3)
for value in set:
print(value) # prints 1, 3, 5 - automatically sorted, regardless of
# the order they were inserted inThe reason a sorted set stays efficient despite automatic sorting lies in its internal structure: a balanced search tree (e.g. a red-black tree) keeps its elements so that every node is at most twice as deeply nested as any other — this keeps inserting, searching, and removing at O(log n) instead of the O(n) of a sorted list, where every insert might have to shift all subsequent elements.
A sorted set is especially suitable for cases where you regularly need range queries (“all values between 10 and 50”) or always want to quickly find the smallest/largest element — both are either impossible or only possible with a full traversal of all elements for an unsorted HashSet, while the sorted tree can answer these questions much more specifically thanks to its structure.
The trade-off against HashSet: pure inserting/searching/removing (with no sorting need) is on average still somewhat faster for a HashSet (O(1) instead of O(log n)) — a sorted set is therefore only worthwhile when the sort order is actually needed, not as a default replacement for a simple HashSet.