Java TreeSet

The Java TreeSet Class

The TreeSet class is an implementation of the Set interface that uses a tree structure (specifically, a Red-Black Tree) for storage.

The most important feature of a TreeSet is that it stores its elements in a sorted order.


Key Characteristics of TreeSet


How TreeSet Works

A TreeSet is backed by a TreeMap. When you add an element, it is placed into the underlying tree structure based on its comparison to the other elements. This comparison is done using either the element's compareTo() method (if the class implements the Comparable interface) or a Comparator provided to the TreeSet's constructor.

This tree structure is always kept balanced, which guarantees the O(log n) performance for operations.


When to Use TreeSet

TreeSet is the perfect choice when you need a collection that:

  1. Guarantees uniqueness of elements.
  2. Requires the elements to be always stored in a sorted order.

If you don't need sorting, HashSet or LinkedHashSet will provide better performance.


TreeSet Example

Here is an example demonstrating the sorting behavior of a TreeSet.

Working with `TreeSet`

import java.util.TreeSet;

public class Main { public static void main(String[] args) { // Create a TreeSet of Integers TreeSet numbers = new TreeSet<>(); // Add items numbers.add(50); numbers.add(10); numbers.add(80); numbers.add(10); // This will be ignored // The elements are automatically sorted System.out.println("Sorted TreeSet: " + numbers); // NavigableSet methods System.out.println("First element: " + numbers.first()); System.out.println("Last element: " + numbers.last()); System.out.println("Element higher than 50: " + numbers.higher(50)); System.out.println("Element lower than 50: " + numbers.lower(50)); } }