TreeSet ClassThe 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.
TreeSetSet implementations, it does not allow duplicate elements.Comparator.null Elements: TreeSet does not allow null elements, as it cannot compare null to other elements for sorting.add, remove, and contains operations is O(log n), which is slower than HashSet's O(1).TreeSet implements the NavigableSet interface, which provides useful methods for finding elements relative to others in the sorted set (e.g., floor(), ceiling(), higher(), lower()).TreeSet WorksA 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.
TreeSetTreeSet is the perfect choice when you need a collection that:
If you don't need sorting, HashSet or LinkedHashSet will provide better performance.
TreeSet ExampleHere is an example demonstrating the sorting behavior of a 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)); } }