Java TreeSet
Introduction#
In the Java Collection Framework, TreeSet
is a class that implements the NavigableSet
interface and indirectly implements the SortedSet
interface, which in turn extends the Set
interface. It stores elements in a sorted (natural or custom) order and is part of the java.util
package. Internally, it is backed by a Red-Black Tree, a self-balancing binary search tree. Unlike HashSet
and LinkedHashSet
, TreeSet
does not allow null
elements and ensures that elements are always sorted.
Key Features#
- Stores unique elements like any
Set
. - Maintains elements in sorted order.
- Implements
SortedSet
andNavigableSet
interfaces. - Does not allow null elements.
- Backed by a Red-Black Tree.
Classes Implemented by TreeSet#
Here TreeSet implements NavigableSet and NavigableSet extends SortedSet, therefore TreeSet Implements SortedSet interface indirectly.
SortedSet Interface#
SortedSet
is a subinterface of Set
that maintains elements in a sorted order.
A TreeSet
implements this interface to keep elements automatically sorted in natural order or using a custom comparator.
Constructors#
Explanation:#
- The default constructor creates an empty
TreeSet
that will be sorted according to the natural ordering of its elements. - The constructor with
Comparator
allows for custom sorting. - The constructor with
Collection
copies elements and maintains the sorted order. - The constructor with
SortedSet
creates aTreeSet
with the same ordering as the provided sorted set.
Commonly Used Methods#
Method | Description |
---|---|
add(E e) | Adds the specified element. Throws NullPointerException if element is null. |
remove(Object o) | Removes the specified element if present. |
contains(Object o) | Returns true if the element is present. |
isEmpty() | Checks if the set is empty. |
size() | Returns the number of elements. |
clear() | Removes all elements. |
first() | Returns the lowest element. |
last() | Returns the highest element. |
headSet(E toElement) | Returns elements strictly less than toElement . |
tailSet(E fromElement) | Returns elements greater than or equal to fromElement . |
subSet(E fromElement, E toElement) | Returns elements ranging from fromElement (inclusive) to toElement (exclusive). |
Example: Basic Usage#
Output:#
Explanation:#
The numbers are automatically sorted in ascending order (natural ordering). Duplicates are not allowed, and TreeSet
ensures sorted uniqueness.
Example: Navigable Methods#
Output:#
Explanation:#
first()
returns the lowest element in the set.last()
returns the highest element.headSet(30)
returns elements strictly less than 30.tailSet(20)
returns elements greater than or equal to 20.subSet(10, 30)
returns elements from 10 (inclusive) to 30 (exclusive).
Performance#
Operation | Time Complexity |
---|---|
add(E e) | O(log n) |
remove(Object o) | O(log n) |
contains(Object o) | O(log n) |
iteration | O(n) |
Explanation:#
Due to the Red-Black Tree structure, insertions, deletions, and lookups are all logarithmic in time. Iterating through the set is linear.
Null Handling#
Explanation:#
TreeSet
does not allow null
elements because it uses comparisons to sort elements, and comparing null
with other objects throws a NullPointerException
.
Custom Comparator#
You can sort elements in a custom order using a comparator:
Output:#
Explanation:#
We passed a reverse order comparator to the TreeSet
constructor, so the elements are sorted in descending order.
Key Takeaways:#
TreeSet
stores unique, sorted elements.- Sorting can be natural (by default) or custom (via
Comparator
). - Null elements are not allowed.
- Operations like add, remove, and search take O(log n) time.
Use TreeSet
when:
- You need sorted order and uniqueness.
- You don't need to allow nulls.
- Slightly lower performance than
HashSet
is acceptable in exchange for automatic ordering.
Conclusion#
In this blog, we explored the TreeSet
class in detail. We discussed its characteristics, method usage, and how it maintains elements in sorted order using a Red-Black Tree. We also looked at performance, null handling, and how to apply custom sorting with a comparator.