Table of contents
1.
Introduction
2.
What is TreeSet?
3.
TreeSet Constructors
4.
TreeSet Methods
5.
Frequently Asked Questions
5.1.
When will a TreeSet throw a NullPointerException?
5.2.
Is the TreeSet synchronized?
5.3.
What is the time complexity of a TreeSet?
5.4.
What is the difference between HashSet and TreeSet.
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

TreeSet

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

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.

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()
        ts.add("1");
        ts.add("4");
        ts.add("2");
        ts.add("0");

        //printing the TreeSet
        System.out.println("TreeSet is: " + ts);
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

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()
        ts.add(5);
        ts.add(1);
        ts.add(7);
        ts.add(3);
        ts.add(6);
        ts.add(0);

        // 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
        System.out.println(ts_1);
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

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

Methods

Description

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.

last()

 

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.

pollFirst()

 

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.

HashSet

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

Conclusion

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!

Live masterclass