Skip to content
Related Articles

Related Articles

Difference Between TreeSet and SortedSet in Java
  • Last Updated : 25 Mar, 2021
GeeksforGeeks - Summer Carnival Banner

TreeSet is one of the implementations of the SortedSet interface in Java that uses a Red-black tree for storage. By default, the elements are stored in ascending order. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used.

  • It also implements NavigableSet interface.
  • NavigableSet extends SortedSet and Set interfaces.



// Java program to demonstrate the TreeSet
import java.util.*;
class Main {
    public static void main(String args[])
        // Creating and adding elements
        TreeSet<String> al = new TreeSet<String>();
        // Add elements
        al.add("Geeks for Geeks");
        // Traversing elements
        Iterator<String> itr = al.iterator();
        while (itr.hasNext()) {
Geeks for Geeks

Sorted Set:

The SortedSet interface is available in java.util package which extends the Set interface. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this interface to be stored in a sorted manner.



// Java program to demonstrate the
// Sorted Set
import java.util.*;
class Main {
    public static void main(String[] args)
        // create an instance of sortedset
        SortedSet<String> ts = new TreeSet<String>();
        // Adding elements into the TreeSet
        // using add()
        // Adding the duplicate
        // element
        // Displaying the TreeSet
        // Removing items from TreeSet
        // using remove()
        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator<String> i = ts.iterator();
        while (i.hasNext())
[Bobby, Devi2, Gnanesh, Ojaswi, Rohith, Sravan]
Iterating over set:

Differences between TreeSet and SortedSet



TreeSet is a concrete class.SortedSet is an interface.
TreeSet allows a heterogeneous object.SortedSet allows a heterogeneous object.
TreeSet maintains an object in sorted order.SortedSet maintains an object in sorted order.


TreeSet<String> treeset = new TreeSet<String>();


It can not be instantiated as it is a Interface

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :