TreeSet In Java: Tutorial With Programming Examples

This Tutorial Explains all about TreeSet Class, Implementation, Iteration, TreeSet Vs HashSet, Java TreeSet Examples, etc.:

TreeSet in Java implements the Set interface (more specifically SortedSet). The TreeSet uses a TreeMap internally for storing data. By default, the objects or elements of the TreeSet are stored according to the natural ordering in ascending order.

The TreeSet class that implements TreeSet in Java implements the ‘NavigableSet’ interface and also inherits the AbstractSet class.

=> Check Here To See A-Z Of Java Training Tutorials Here.

TreeSet in Java

Note that the TreeSet elements can also be explicitly ordered by providing the customized Comparator at the time of creating a TreeSet object using the specific constructor prototype.

Given below are some of the important characteristics of TreeSet:

  1. TreeSet class implements the SortedSet interface. It doesn’t allow duplicate elements.
  2. TreeSet class is not synchronized.
  3. TreeSet does not preserve the insertion order but the elements in TreeSet are sorted as per the natural ordering.
  4. TreeSet can be ordered by using a custom comparator while creating a TreeSet object.
  5. TreeSet is normally used for storing huge amounts of information that is naturally sorted. This aids in easy and faster access.

TreeSet Class Declaration

Java provides a class called “TreeSet” that contains the functionality of TreeSet data structure. The TreeSet class is a part of java.util package.

To include the TreeSet class in the Java program, we should use the import statement as given below:

import java.util.TreeSet;

or

import java.util.*;

A general declaration of TreeSet class is:

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

As seen from the class declaration, TreeSet class extends AbstractSet and implements NavigableSet, Cloneable, and Serializable interfaces.

A class hierarchy for TreeSet class is given below:

class hiearachy for TreeSet

Internal Implementation

We know that TreeSet implements the NavigableSet interface and extends the SortedSet class.

Internally, the TreeSet constructor is defined as follows:

public TreeSet() {
 this(new TreeMap<E,Object>());
 }

As seen in the above constructor definition of TreeSet, a TreeMap object is invoked. Thus internally, it is a TreeMap object that is implemented for a TreeSet. Hence while adding an element to TreeSet, a key is added to TreeMap in which the keys are sorted by default.

As per Oracle documentation on TreeSet,

“A TreeSet is a NavigableSet implementation based on a TreeMap.”

Java TreeSet Example

The following Java program shows a simple example that demonstrates TreeSet. In this program, we have defined a simple Color TreeSet. We add elements to it and then display it. Note that the elements are displayed as per the natural ordering.

 import java.util.*;
class Main{
 public static void main(String args[]){
  //Create and add elements to TreeSet
  TreeSet&amp;amp;lt;String&amp;amp;gt; color_TreeSet=new TreeSet&amp;amp;lt;String&amp;amp;gt;();
  color_TreeSet.add(&amp;amp;quot;Red&amp;amp;quot;);
  color_TreeSet.add(&amp;amp;quot;Green&amp;amp;quot;);
  color_TreeSet.add(&amp;amp;quot;Blue&amp;amp;quot;);
  color_TreeSet.add(&amp;amp;quot;Yellow&amp;amp;quot;);
  //Traverse the TreeSet and print elements one by one
  System.out.println(&amp;amp;quot;TreeSet Contents:&amp;amp;quot;);
  Iterator&amp;amp;lt;String&amp;amp;gt; iter=color_TreeSet.iterator();
  while(iter.hasNext()){
   System.out.print(iter.next() + &amp;amp;quot;\t&amp;amp;quot;);
  }
 }
}

Output:

TreeSet Contents:
Blue Green Red Yellow

output - TreeSet Implementation

Iterate Through TreeSet

To access the individual elements of TreeSet, we need to iterate through the TreeSet or in other words, traverse through the TreeSet.

We do this by declaring an Iterator for the TreeSet and then using this Iterator to access each element. For this, we use the next () method of an iterator that returns the next element in the TreeSet.

The following Java program demonstrates the use of the Iterator to iterate through TreeSet.

import java.util.TreeSet;
import java.util.Iterator;

class Main {
    public static void main(String[] args) {
        //create and initialize TreeSet
        TreeSet&amp;amp;lt;Integer&amp;amp;gt; num_Treeset = new TreeSet&amp;amp;lt;&amp;amp;gt;();
        num_Treeset.add(20);
        num_Treeset.add(5);
        num_Treeset.add(15);
        num_Treeset.add(25);
        num_Treeset.add(10);
        System.out.println(&amp;amp;quot;TreeSet: &amp;amp;quot; + num_Treeset);

        // Call iterator() method to define Iterator for TreeSet
        Iterator&amp;amp;lt;Integer&amp;amp;gt; iter_set = num_Treeset.iterator();
        System.out.print(&amp;amp;quot;TreeSet using Iterator: &amp;amp;quot;);
        // Access TreeSet elements using Iterator
        while(iter_set.hasNext()) {
            System.out.print(iter_set.next());
            System.out.print(&amp;amp;quot;, &amp;amp;quot;);
        }
    }
}

Output:

TreeSet: [5, 10, 15, 20, 25]
TreeSet using Iterator: 5, 10, 15, 20, 25,

use of the Iterator output

TreeSet Comparator In Java

By default, the TreeSet is naturally ordered. We can also sort TreeSet in a customized order by defining a new comparator class. In this comparator class, we need to override the ‘compare’ method to sort the elements of the TreeSet. This comparator object is then passed to the TreeSet constructor.

The following Java program shows the use of a Comparator to sort the TreeSet.

import java.util.TreeSet;
import java.util.Comparator;
class Main {
    public static void main(String[] args) {
        // Create a TreeSet with user-defined comparator
        TreeSet&amp;amp;lt;String&amp;amp;gt; cities = new TreeSet&amp;amp;lt;&amp;amp;gt;(new cities_Comparator());
        //add elements to the comparator
        cities.add(&amp;amp;quot;Pune&amp;amp;quot;);
        cities.add(&amp;amp;quot;Hyderabad&amp;amp;quot;);
        cities.add(&amp;amp;quot;Indore&amp;amp;quot;);
        cities.add(&amp;amp;quot;Bangaluru&amp;amp;quot;);
        //print the contents of TreeSet
        System.out.println(&amp;amp;quot;TreeSet: &amp;amp;quot; + cities);
    }
    // Create a comparator class
    public static class cities_Comparator implements Comparator&amp;amp;lt;String&amp;amp;gt; {
        //override compare method to compare two elements of the TreeSet
        @Override
        public int compare(String cities_one, String cities_two) {
            int value =  cities_one.compareTo(cities_two);
            // sort elements in reverse order
            if (value &amp;amp;gt; 0) {
                return -1;
            }
            else if (value &amp;amp;lt; 0) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }
}

Output:

TreeSet: [Pune, Indore, Hyderabad, Bangaluru]

program shows the use of a Comparator output

The above program implements a Comparator class to sort the given TreeSet alphabetically in reverse order.

Recommended Reading =>> Java Comparator Interface

TreeSet API/Methods & Constructors

In this section, we will discuss the API of the TreeSet class. Here we will discuss the constructors and methods provided by the TreeSet class.

TreeSet class provides overloaded constructors to construct a TreeSet object.

We have tabularized these constructors as follows:

Constructors

Methods

Next, let’s tabularize the various methods provided by the TreeSet class.

TreeSet In Java 8

Please note that for TreeSet, there are no major changes in the Java 8 version. All methods and constructors work in Java 8 and the later versions.

TreeSet Implementation In Java

The following Java program implements most of the TreeSet methods discussed above.

import java.util.Iterator;
import java.util.TreeSet;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        //create a TreeSet of numbers
        TreeSet&amp;amp;lt;Integer&amp;amp;gt; numSet = new TreeSet&amp;amp;lt;Integer&amp;amp;gt;();
        //add () method
        numSet.add(30);
        numSet.add(10);
        //declare and initialize an ArrayList
        ArrayList&amp;amp;lt;Integer&amp;amp;gt; myList = new ArrayList&amp;amp;lt;Integer&amp;amp;gt;();
        myList.add(15);
        myList.add(25);
        myList.add(35);
        //addAll () method : add ArrayList elements to TreeSet
        numSet.addAll(myList);
        //define an iterator on TreeSet
        Iterator&amp;amp;lt;Integer&amp;amp;gt; iterator = numSet.iterator();
        System.out.print(&amp;amp;quot;Tree set contents: &amp;amp;quot;);
        while (iterator.hasNext())
            System.out.print(iterator.next() + &amp;amp;quot; &amp;amp;quot;);
        System.out.println();
        //ceiling ()
        System.out.println(&amp;amp;quot;ceiling(25):&amp;amp;quot; + numSet.ceiling(25));
        //floor ()
        System.out.println(&amp;amp;quot;floor(25):&amp;amp;quot; + numSet.floor(25));
        //contains ()
        System.out.println(&amp;amp;quot;TreeSet contains(15):&amp;amp;quot; + numSet.contains(15));

        // isEmpty ()
        if (numSet.isEmpty())
            System.out.print(&amp;amp;quot;Tree Set is empty.&amp;amp;quot;);
        else
            System.out.println(&amp;amp;quot;Tree Set size: &amp;amp;quot; + numSet.size()); 

       // first ()
        System.out.println(&amp;amp;quot;TreeSet First element: &amp;amp;quot; + numSet.first()); 

        // last ()
        System.out.println(&amp;amp;quot;TreeSet Last element: &amp;amp;quot; + numSet.last()); 

        // remove ()
        if (numSet.remove(30))
            System.out.println(&amp;amp;quot;Element 30 removed from TreeSet&amp;amp;quot;);
        else
            System.out.println(&amp;amp;quot;Element 30 doesn't exist!&amp;amp;quot;); 

        System.out.print(&amp;amp;quot;TreeSet after remove (): &amp;amp;quot;);
        iterator = numSet.iterator();
        while (iterator.hasNext())
            System.out.print(iterator.next() + &amp;amp;quot; &amp;amp;quot;);
        System.out.println();
        //size ()
        System.out.println(&amp;amp;quot;TreeSet size after remove (): &amp;amp;quot; + numSet.size());
        //Headset ()
        System.out.println(&amp;amp;quot;Headset : &amp;amp;quot; + numSet.headSet(35));
        // clear ()
        numSet.clear();
        System.out.println(&amp;amp;quot;Tree Set size after clear (): &amp;amp;quot; + numSet.size());
    }
}

Output:

Tree set contents: 10 15 25 30 35
ceiling(25):25
floor(25):25
TreeSet contains(15):true
Tree Set size: 5
TreeSet First element: 10
TreeSet Last element: 35
Element 30 removed from TreeSet
TreeSet after remove (): 10 15 25 35
TreeSet size after remove (): 4
Headset : [10, 15, 25]
Tree Set size after clear (): 0

Java program implements most of the TreeSet methods - Output

In the above program, we define a TreeSet object and then add elements to it using the ‘add’ method. Next, we define an ArrayList. Then we add elements of ArrayList to TreeSet using the ‘addAll’ method. Later, we demonstrate various TreeSet methods like Iterator, ceiling, floor, first, last, contains, size, isEmpty, etc.

TreeSet Vs HashSet

Let’s check out some of the differences between TreeSet and HashSet.

Frequently Asked Questions

1. What is a TreeSet?

TreeSet is an implementation of SortedSet that does not allow duplicate values. The elements in the TreeSet are by default sorted in ascending order.

2. How do you add elements to TreeSet in Java?

TreeSet class provides an additional method that is used to add a specific element to the TreeSet. It also provides the ‘addAll’ method. This method accepts any other collection as an argument and then adds all the elements of this collection to the TreeSet.

3. Is TreeSet thread-safe?

No. TreeSet is not thread-safe. Thus we should take care of how we operate TreeSet in a multi-threaded environment.

4. Can TreeSet have duplicates?

No. TreeSet does not allow duplicates.

5. Does TreeSet allow null in Java?

Yes. We can have null elements in TreeSet.


Conclusion

This completes our tutorial on TreeSet. TreeSet is a SortedSet implementation that does not allow duplicates but allows null values. The elements in the TreeSet are by default sorted according to natural ordering in ascending order.

We have seen the basics of the TreeSet class along with its declaration and various constructors & methods.

In our subsequent tutorials, we discuss the remaining Java collection classes.

=> Watch Out for The Simple Java Training Series Here.

Was this helpful?

Thanks for your feedback!