TreeSet in Java
TreeSet in Java is a class that implements NavigableSet and stores unique elements in sorted order. It is used when you need a set whose elements always come out sorted, or when you need range and nearest-value searches. Inside, TreeSet uses a self-balancing binary search tree called a red-black tree, so adding, removing and searching take logarithmic time. In this lesson, you will learn how to create a TreeSet, sort it in natural or custom order, and avoid its common pitfalls.
Declaration
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, SerializableFeatures of TreeSet
- Sorted: elements are kept in natural order or in the order of a comparator.
- Unique: duplicates, as decided by
compareToor the comparator, are ignored. - No
null: addingnullthrowsNullPointerException, becausenullcan't be compared. - O(log n) for
add,removeandcontains. - Navigable: supports
floor,ceiling,headSet,tailSetand more. - Not synchronized.
Constructors
| Constructor | Description |
|---|---|
TreeSet() | It creates an empty set sorted in natural order. |
TreeSet(Comparator<? super E> c) | It creates an empty set sorted by the comparator. |
TreeSet(Collection<? extends E> c) | It creates a set with the elements of a collection, in natural order. |
Example: Natural and Custom Order
Let's see an example of two TreeSets holding the same names.
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
List<String> names = List.of("Srihitha", "Navika", "Advitha",
"Anamaneni", "Navika");
TreeSet<String> natural = new TreeSet<>(names);
System.out.println("Natural: " + natural);
TreeSet<String> byLength = new TreeSet<>(
Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
byLength.addAll(names);
System.out.println("By length: " + byLength);
System.out.println("First: " + natural.first()
+ ", last: " + natural.last());
}
}Natural: [Advitha, Anamaneni, Navika, Srihitha]
By length: [Navika, Advitha, Srihitha, Anamaneni]
First: Advitha, last: SrihithaExplanation: Both sets drop the second Navika. The first sorts alphabetically. The second sorts by length, and names with the same length are then sorted alphabetically.
The Comparator Decides What Is a Duplicate
If the comparator says two elements are equal (returns 0), TreeSet keeps only the first, even when the elements are different:
import java.util.Comparator;
import java.util.TreeSet;
public class LostElements {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<>(
Comparator.comparingInt(String::length));
set.add("Navika");
set.add("Advitha");
set.add("Anamaneni");
set.add("Mumbai");
System.out.println(set);
}
}[Navika, Advitha, Anamaneni]Explanation: "Mumbai" has 6 letters, like "Navika", so the comparator returns 0 and the set treats it as a duplicate. That is why the earlier example added thenComparing(Comparator.naturalOrder()) to break ties.
Common Mistakes
Adding null to a TreeSet. It throws NullPointerException.
Storing a class that is neither Comparable nor given a comparator. The first add throws ClassCastException.
Using a comparator that ignores some fields. Different elements can silently disappear.
Interview Corner
What is the difference between HashSet and TreeSet?
HashSet stores elements in a hash table with no order and offers O(1) average add, remove and contains; it uses hashCode and equals and allows one null. TreeSet stores elements in a red-black tree in sorted order, with O(log n) operations; it uses compareTo or a comparator to order elements and detect duplicates, doesn't allow null, and supports navigation methods such as floor, ceiling and headSet.
Practice
- Easy: Read five words and print them in sorted order without duplicates.
- Harder: Store
Studentrecords in aTreeSetsorted by marks from highest to lowest, making sure students with equal marks are not lost.
Key Takeaways
Was this tutorial helpful?