December 2, 2025By

TreeSet in Java

In Java, the TreeSet class is a part of the java.util package and implements the Set interface, which means it does not allow duplicate elements. It is a collection that stores unique elements in a sorted order, based on their natural ordering or a specified comparator. The underlying data structure that makes the TreeSet class work is a Red-Black Tree, which is a balanced binary search tree. This tree structure ensures that the elements are always sorted and provides efficient operations for insertion, deletion, and retrieval of elements. TreeSet in Java offers a sorted, unique collection with fast search and navigation, ideal for managing ordered data efficiently for modern tasks

In this article, we will explore the definition, constructors, internal workings, methods, performance characteristics, and user-defined TreeSets in Java.

Definition of TreeSet

The TreeSet class is a NavigableSet that extends the AbstractSet class and implements the Set interface. It does not allow duplicates and stores elements in a sorted order, meaning that when you iterate over a TreeSet, the elements are returned in ascending order (by default). A TreeSet can also be customized to use a specific sorting order by providing a Comparator during the creation of the set.

A TreeSet is particularly useful when you need to maintain a sorted collection of unique elements, and when operations such as searching, adding, and removing elements need to be efficient.

### Key Features of TreeSet

• Stores only unique elements.

• Automatically sorts elements in ascending order.

• Does not maintain insertion order.

• Duplicate values are not allowed.

• Null values are generally not allowed.

• Provides many navigation methods like higher(), lower(), first(), last(), ceiling(), and floor().

• Uses a Red-Black Tree internally.

TreeSet in Java

TreeSet Java is a class in the Java Collections Framework that implements the SortedSet interface and stores elements in a sorted order. It is commonly used when developers need to maintain a collection of unique elements while keeping them automatically sorted. TreeSet is typically implemented using a Red-Black tree, which provides efficient operations such as insertion, deletion, and searching. It does not allow duplicate elements and generally does not permit null elements when natural ordering is used. Understanding TreeSet Java is important for developers working with collections where maintaining sorted and unique data is required.

Constructors of TreeSet -

The TreeSet class provides several constructors, allowing for different initialization options. Here are the main binary tree in java constructors:

  1. 1. TreeSet()
  2. This constructor creates an empty TreeSet that uses the natural ordering of its elements (i.e., elements must be Comparable).
  3. 2. TreeSet<Integer> treeSet = new TreeSet<>();
  4. 3. TreeSet(Comparator<? super E> comparator)
  5. This constructor creates a TreeSet that uses the specified comparator for ordering the elements.
  6. 4. TreeSet<Integer> treeSet = new TreeSet<>(Comparator.reverseOrder());
  7. 5. TreeSet(Collection<? extends E> c)
  8. This constructor creates a TreeSet initialized with the elements of the specified collection. The elements are sorted according to their natural ordering or by a comparator, if provided.
  9. 6. List<Integer> list = Arrays.asList(1, 2, 3);
  10. 7. TreeSet<Integer> treeSet = new TreeSet<>(list);
  11. 8. TreeSet(SortedSet<E> s)
  12. This constructor creates a TreeSet that contains the elements of the specified SortedSet and maintains their order.
  13. 9. SortedSet<Integer> sortedSet = new TreeSet<>();
  14. 10. TreeSet<Integer> treeSet = new TreeSet<>(sortedSet)

Internal Working of TreeSet

Internally, a TreeSet uses a Red-Black Tree to store its elements. The Red-Black Tree is a balanced binary search tree that ensures that the tree remains balanced after every insertion and deletion operation. This helps guarantee logarithmic time complexity for most operations, such as adding, removing, and searching for elements.

A Red-Black Tree maintains the following properties:

  • • Every node is either red or black.
  • • The root is always black.
  • • Every leaf (NIL) is black.
  • • No two red nodes can be next to each other; hence, any offspring of a red node must be black.
  • • The number of black nodes on each path from a node to its descendant leaves is the same.

These properties ensure that the height of the tree is always O(log n), leading to efficient time complexity for operations such as adding, deleting, and searching elements.

When an element is added to the TreeSet, it is inserted into the Red-Black Tree according to its ordering, and the tree is adjusted to maintain the balance. The sorting of the elements is based on their natural order or a comparator provided during the initialization of the TreeSet.

TreeSet Methods

The TreeSet class provides a rich set of methods that help in performing various operations. Some of the commonly used methods are:

  1. 1. add(E e)
  2. If the given element is not already in the set, it is added. The element is inserted in a sorted order.

treeSet.add(10);

  1. 2. remove(Object o)
  2. Removes the specified element from the set if it exists.

treeSet.remove(10);

  1. 3. contains(Object o)
  2. Returns true if the given element is present in the set.
  3. boolean isPresent = treeSet.contains(10);
  4. 4. size()
  5. Returns the number of elements in the set.

int size = treeSet.size();

  1. 5. isEmpty()
  2. Returns true if the set contains no elements.

boolean isEmpty = treeSet.isEmpty();

  1. 6. clear()
  2. Removes all elements from the set.

treeSet.clear();

  1. 7. first()
  2. Returns the first (lowest) element in the set.

Integer firstElement = treeSet.first();

  1. 8. last()
  2. Returns the last (highest) element in the set.

Integer lastElement = treeSet.last();

  1. 9. pollFirst()
  2. Removes and returns the first (lowest) element in the set.

Integer first = treeSet.pollFirst();

  1. 10. pollLast()
  2. Removes and returns the last (highest) element in the set.

Integer last = treeSet.pollLast();

  1. 11. subSet(E fromElement, E toElement)
  2. Returns a view of the portion of this set whose elements range from fromElement to toElement, excluding the element toElement.

SortedSet<Integer> subset = treeSet.subSet(10, 20);

  1. 12. headSet(E toElement)
  2. Returns a view of the portion of this set whose elements are less than toElement.

SortedSet<Integer> headSet = treeSet.headSet(20);

  1. 13. tailSet(E fromElement)
  2. Returns a view of the portion of this set whose elements are greater than or equal to fromElement.

SortedSet<Integer> tailSet = treeSet.tailSet(10);

  1. 14. iterator()
  2. Returns an iterator over the elements in the set in ascending order.

Iterator<Integer> iterator = treeSet.iterator();

User-Defined TreeSet Example with Custom Class (Actor)

import java.util.*;

class Actor {

int id;


String name;


String movie;


public Actor(int id, String name, String movie) {


    this.id = id;


    this.name = name;


    this.movie = movie;


}


@Override


public String toString() {


    return "Actor{id=" + id + ", name='" + name + "', movie='" + movie + "'}";


}


}

public class TreeSetActorExample {

public static void main(String[] args) {


    Comparator<Actor> sortById = new Comparator<Actor>() {


        @Override


        public int compare(Actor a1, Actor a2) {


            return Integer.compare(a1.id, a2.id);


        }


    };


    TreeSet<Actor> actorSet = new TreeSet<>(sortById);


    actorSet.add(new Actor(3, "Vijay", "Leo"));


    actorSet.add(new Actor(1, "Prabhas", "Salaar"));


    actorSet.add(new Actor(2, "Yash", "KGF"));


    actorSet.add(new Actor(4, "Rajinikanth", "Jailer"));


    for (Actor a : actorSet) {


        System.out.println(a);


    }


}


}

Performance of TreeSet

The performance of TreeSet is largely influenced by the underlying Red-Black Tree data structure. Since the Red-Black Tree maintains a balanced structure, most operations on the TreeSet have a time complexity of O(log n), where n is the number of elements in the set. This includes:

  • • Insertion (add(E e))
  • • Deletion (remove(Object o))
  • • Searching (contains(Object o))

However, operations that require traversal, such as iterating over the set or getting subsets, will typically involve visiting all elements, which has a time complexity of O(n) in the worst case.

Key Performance Characteristics:

  • • Insertion: O(log n)
  • • Deletion: O(log n)
  • • Search (Contains): O(log n)
  • • Accessing elements: O(n) for iterating
  • • Memory Complexity: O(n) for storing n elements

Real-Time Applications of TreeSet

TreeSet is useful in many real-world applications.

1. Student Roll Numbers

Schools can store unique roll numbers in sorted order.

2. Employee IDs

Companies can maintain employee IDs without duplicates.

3. Dictionary Applications

Words can be displayed alphabetically.

4. Online Ticket Booking

Seat numbers can be stored in sorted order.

5. Leaderboards

Scores or ranks can be managed efficiently.

6. Banking Systems

Unique account numbers can be maintained in sorted format.

7. Product Codes

Shopping websites can store product IDs without duplicates.

Advantages of TreeSet

• Automatically sorts data.

• Duplicate values are removed automatically.

• Searching is efficient.

• Provides many navigation methods.

• Suitable for sorted collections.

Limitations of TreeSet

• Slower than HashSet because sorting is maintained.

• Does not preserve insertion order.

• Null values are generally not allowed.

• Random access is not available.

Best Practices

• Use TreeSet when you need sorted data.

• Use HashSet if sorting is not required and better performance is needed.

• Implement Comparable or provide a Comparator for custom objects.

• Avoid inserting null values.

• Choose TreeSet only when sorted and unique data is required.

Interview Questions

1. What is TreeSet?

TreeSet is a class in the Java Collection Framework that stores unique elements in sorted order.

2. Does TreeSet allow duplicate values?

No. Duplicate values are automatically ignored.

3. Does TreeSet maintain insertion order?

No. It maintains sorted order.

4. Which data structure does TreeSet use?

Red-Black Tree.

5. Can TreeSet store null values?

Generally, no.

6. What is the time complexity of add(), remove(), and contains()? The average time complexity is O(log n).

7. Which interface does TreeSet implement?

NavigableSet, which extends SortedSet.

Conclusion

The TreeSet class in Java, binary tree in java is a powerful and efficient collection for managing unique elements in a sorted order. It ensures that the elements are sorted either by their natural order or by a custom comparator, providing flexibility. The underlying Red-Black Tree structure guarantees efficient operations, with most operations having a time complexity of O(log n). The TreeSet is ideal for scenarios where ordering and uniqueness are essential, and its ability to offer efficient search, insertion, and removal operations makes it a valuable tool in Java development.

Do visit our channel to explore more: SevenMentor

Written by the SevenMentor training team, who teach IT and professional courses across our branches and online.

#Technology#Education#Career Guidance