TreeSet in Java

Naveen AnamaneniUpdated · 4 min read

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

Declaration
public class TreeSet<E> extends AbstractSet<E>
        implements NavigableSet<E>, Cloneable, Serializable

Features of TreeSet

  • Sorted: elements are kept in natural order or in the order of a comparator.
  • Unique: duplicates, as decided by compareTo or the comparator, are ignored.
  • No null: adding null throws NullPointerException, because null can't be compared.
  • O(log n) for add, remove and contains.
  • Navigable: supports floor, ceiling, headSet, tailSet and more.
  • Not synchronized.

Constructors

ConstructorDescription
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.

TreeSetDemo.java▶ Try it
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());
    }
}
Output
Natural:   [Advitha, Anamaneni, Navika, Srihitha]
By length: [Navika, Advitha, Srihitha, Anamaneni]
First: Advitha, last: Srihitha

Explanation: 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:

LostElements.java▶ Try it
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);
    }
}
Output
[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

  1. Easy: Read five words and print them in sorted order without duplicates.
  2. Harder: Store Student records in a TreeSet sorted by marks from highest to lowest, making sure students with equal marks are not lost.

Quick check: TreeSet

4 questions
1What structure does TreeSet use internally?
2What happens when you add null to a TreeSet?
3What does TreeSet use to detect duplicates?
4What is the cost of contains in a TreeSet?

Key Takeaways

Was this tutorial helpful?

Lesson 276 of 482