TreeSet

TreeSet is a part of the Java Collections Framework and implements the Set interface, which means it doesn’t allow duplicate elements. However, the key feature of a TreeSet is that it stores the elements in a sorted order (ascending by default). It is based on a TreeMap, meaning it uses a Red-Black tree to store elements.

Features

  • Sorted Order: Elements are stored in ascending order by default. You can also provide a custom order using a comparator.
  • No Duplicates: Unlike lists, a TreeSet does not allow duplicate values. If an attempt to add a duplicate is made, it is ignored.
  • Efficient Operations: Operations like add, remove, and contains are performed in log(n) time complexity.
  • NavigableSet: TreeSet implements the NavigableSet interface, which allows navigating the set using methods like lower(), higher(), etc.

Example

Use Cases

  • Unique Sorted Data: If you need a collection that stores unique elements in a specific order, a TreeSet is ideal.
  • Range Queries: Due to its navigability, TreeSet is useful for tasks where you need to find elements within a certain range, or locate the closest higher or lower elements.
  • Maintaining Order: If maintaining an ordered list of elements is essential (like a leaderboard or ranking system), TreeSet is the perfect choice.