Course contentsShow
← Java
Lesson 1066 of 2,87025. Set ImplementationsFree lesson

What is TreeSet? Sorted Set Fundamentals

Understand TreeSet as a NavigableSet implementation that maintains elements in sorted order using a red-black tree.

What is TreeSet? Sorted Set Fundamentals

What you'll learn: You'll discover what a TreeSet is and how it automatically keeps your elements in sorted order.

The Core Idea

A TreeSet is Java's implementation of a sorted set — a collection that stores unique elements in a specific order. Unlike HashSet, which stores elements in no particular order based on hash codes, TreeSet maintains elements in their natural sorted order (like alphabetically for Strings, or numerically for Integers).

How TreeSet Works

Behind the scenes, TreeSet is backed by a red-black tree, a type of self-balancing binary search tree. Think of it like a family tree where:

  • Each element has a place based on its value
  • Smaller values go to the left, larger values to the right
  • The tree automatically reorganizes itself to stay balanced

This structure ensures that elements are always accessible in sorted order.

TreeSet as a NavigableSet

TreeSet implements the NavigableSet interface, meaning it's not just sorted — it's navigable. You can efficiently find elements that are higher or lower than a given value, get the first or last element, or traverse the set in reverse order.

Key Characteristics

  • Uniqueness: Like all sets, no duplicates allowed
  • Sorted order: Elements are automatically ordered (not insertion order!)
  • No nulls: TreeSet cannot store null (it needs to compare elements)
  • Performance: Operations like add, remove, and contains take O(log n) time due to the tree structure

Key Takeaway: TreeSet is a NavigableSet implementation that uses a red-black tree to automatically maintain elements in sorted order, providing both set semantics (no duplicates) and efficient sorted access.