A TreeSet is a part of Java’s Collection Framework that implements the Set interface and uses a Red-Black Tree internally to store elements in sorted order without duplicates.
TreeSet maintains elements in ascending order by default using their natural ordering or by a custom Comparator provided during creation.
- HashSet: Stores elements in random order, backed by a HashMap.
- TreeSet: Stores elements in sorted order, backed by a TreeMap.
TreeSet allows only one null value, but if you try to add more or compare null with other elements, it throws a NullPointerException because sorting requires comparison.
- Insertion, Deletion, and Search take O(log n) time because TreeSet is based on a balanced Red-Black Tree.
This shows that TreeSet is not limited to natural ordering; it can adapt to your sorting requirements.
TreeSet<String> cities = new TreeSet<>((a, b) -> b.compareTo(a));
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Kolkata");
System.out.println(cities); // [Mumbai, Kolkata, Delhi] (Descending order)