Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Table of contents
What is TreeSet?
TreeSet Constructors
TreeSet Methods
Frequently Asked Questions
When will a TreeSet throw a NullPointerException?
Is the TreeSet synchronized?
What is the time complexity of a TreeSet?
What is the difference between HashSet and TreeSet.
Last Updated: Mar 27, 2024


Crack Google SDE interview : Essential projects
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM


Being a part of the Java Collections framework, the Set interface enables the user to create a mathematical set. This is an extension of the Collections interface. In contrast to lists, sets cannot have duplicate elements. We can't create objects using Set since it's an interface.

To utilize the Set interface's functions, we can use classes such as

This article will learn about the TreeSet classes in Java and their methods.

Also Read About, Multithreading in java

What is TreeSet?

When searching nearby items of an item based on the order of their elements, TreeSet is the best Collection Framework. 

Navigable sets are implemented using TreeSet based on TreeMap. TreeSet constructs each set of elements using its natural ordering or a comparator provided during construction.

The following are various properties of TreeSet:

  • NavigableSet is an implementation class for TreeSet, which is an implementation class for SortedSet.
  • TreeSet uses the Balanced Tree data structure as its underlying Data Structure.
  • TreeSets do not allow duplicate entries. They replace the old entry with the new one if they are equal.
  • The order in which elements are inserted does not matter, but they are sorted accordingly.
  • You will get a runtime exception called ClassCastException if you attempt to add heterogeneous objects to TreeSet.
  • Null insertions will only be accepted once.
  • In TreeMap, elements are inserted, removed, and searched with logarithmic time.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job

TreeSet Constructors

There are four Constructors in a TreeSet: 

  • TreeSet ts = new TreeSet(); //This method creates an empty TreeSet object in which elements are inserted in the natural sorting order.


Here is an example of TreeSet:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        TreeSet ts = new TreeSet();

        //adding elements in the TreeSet using add()

        //printing the TreeSet
        System.out.println("TreeSet is: " + ts);



TreeSet is: [0, 1, 2, 4]


  • TreeSet ts = new TreeSet(Comparator c); //This constructor creates an empty TreeSet object with customized sorting described by the comparator operator.
  • TreeSet ts = new TreeSet(Collection c); //This constructor creates a TreeSet object which consists of all the elements from the collection and stores them in the natural sorting order by default.
  • TreeSet ts = new TreeSet(SortedSet s); //The constructor builds a TreeSet object that holds all elements in the given sorted set in the order they were parsed.


Here is an implementation for the same:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        // Creating TreeSet object
        TreeSet < Integer > ts = new TreeSet < Integer > ();

        // Adding elements in the TreeSet using add()

        // Printing the elements
        System.out.println("TreeSet: " + ts);

        //here we are returning a subset between 4 and 9 to a sortedSet data
        SortedSet < Integer > ss = ts.subSet(4, 9);

        //With the help of sortedSet data we are creating a treeSet
        TreeSet < Integer > ts_1 = new TreeSet < Integer > (ss);

        //printing the new treeset



TreeSet: [0, 1, 3, 5, 6, 7]
[5, 6, 7]


Try it by yourself on java online compiler.

Some points to remember:

  • Objects should be homogeneous and comparable if we rely on the default natural sorting order. Otherwise, we will get a class casting exception runtime error.
  • Comparable objects are those whose corresponding classes implement the Java.lang.comparable interface.
  • This interface is already implemented by the String Class and all wrapper classes. In contrast, StringBuffer does not implement anything similar. As a result, we get a ClassCastException.

TreeSet Methods



add(element) Delete any existing elements from this set and add the specified element instead.
addAll(Collection c) Include the elements in the specified collection in this set.
ceiling(elements) If one is not found, return null. If there is a greater element in the set than the given element, return that element.
clear() All elements get removed from the set.
clone() Recreate the TreeSet instance.
comparator() The comparator is used to order this set's elements, or null if the elements were ordered naturally.
contains(Object o) The element is present if this set contains the element.
descendingIterator() The set of elements in this iterator is returned in descending order.
descendingSet() The elements are returned in reverse order.
first() It returns the element at the end of the list.
floor(element) If there is no such element in the set, it returns null. The greatest element in the set is less than or equal to the given element.
headSet(element) This function returns the elements that are strictly less than the given element.
higher(element) If there is no greater element in this set, it returns null. If the set has no greater element, it returns null.
isEmpty() Sets with no elements return true.
iterator() Iterates through the elements in this set descendingly.



Displays the last element available in this set.
lower(element) This function returns the element in the set with the greatest value strictly less than the given element or null if none exists.



Returns the first element or the lowest element, or null if the set is empty.
pollLast() This removes or retrieves the last element of the set and if the set is empty, this method returns null.
remove(Object) If an element is present, this method removes it from the set.
size() A set's cardinality indicates how many elements are present.

subSet(element_1, element_2)


This function displays the elements between element_1 and element_2.
tailSet(element) This function returns all elements greater than or equal to the element.

Frequently Asked Questions

When will a TreeSet throw a NullPointerException?

Null insertion is possible for empty TreeSets as the first element. However, if we attempt to insert another element after inserting null, we will receive a NullPointerException.

Is the TreeSet synchronized?

A TreeSet cannot be synchronized because a TreeSet can be modified by multiple threads simultaneously, and each thread must update the set within a synchronized manner.
TreeSet ts = Collections.syncronizedSortedSet(new TreeSet());

What is the time complexity of a TreeSet?

A TreeSet's add(), remove(), and contains() methods are guaranteed to be Big O (log n) complex.

What is the difference between HashSet and TreeSet.



An object is compared with a hash set using equals.  Two objects are compared using compare. 
Hashed sets allow null objects.  Tree sets do not allow null objects.
It contains no heterogeneous objects.  It contains heterogeneous objects.

 You can also read about the topic -  hash function in data structure


In this blog, we have seen what is TreeSet in the Collection Framework and also the methods of TreeSet.

Check out this problem - Duplicate Subtree In Binary Tree

We hope that this blog has helped you enhance your knowledge about TreeSet and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Next article
Live masterclass