Open In App

SortedSet Interface in Java with Examples

Last Updated : 08 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The SortedSet interface is present in java.util package that extends the Set interface and stores elements in a sorted order.

Key Features of HashSet

  • Elements are stored in ascending order by default. Allows a custom order using a Comparator.
  • This ensures that no duplicate elements are present, consistent with the Set interface.
  • Null elements are not allowed, especially if natural ordering or a custom comparator is used.
  • HashSet is not thread-safe. It must be synchronized manually for multi-threaded use.

Example: Java Program Implementing SortedSet

Java
import java.util.SortedSet;
import java.util.TreeSet;

public class Geeks {
    
  	public static void main(String args[]) 
    {
        
        // Create a SortedSet of Strings
        SortedSet<String> ss = new TreeSet<>();
        
        System.out.println("SortedSet elements: " + ss);
    }
}

Output
SortedSet elements: []

Hierarchy of SortedSet

Below is the hierarchy diagram of SortedSet, where SortedSet interface extends the Set interface.

Sorted
SortedSet-Heirarchy

Declaration of SortedSet Interface

Syntax:

public interface SortedSet extends Set

Example of a Sorted Set

Java
import java.util.*;

class Geeks {

    public static void main(String[] args)
    {
        SortedSet<String> ts = new TreeSet<String>();

        // Adding elements into the TreeSet using add()
        ts.add("India");
        ts.add("Australia");
        ts.add("South Africa");

        // Adding the duplicate element
        ts.add("India");

        System.out.println(ts);

        // Removing items from TreeSet using remove()
        ts.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + ts);

        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator<String> i = ts.iterator();
      
        while (i.hasNext())
            System.out.println(i.next());
    }
}

Output
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

Note: All elements in a SortedSet must either implement the Comparable interface or be accepted by a given Comparator, and they must be mutually comparable (each object can be compared to another using compareTo).

Creating SortedSet Objects

SortedSet is an interface, so we cannot directly create its objects. Instead, we use a class that implements this interface, such as TreeSet.

// Obj is the type of the object to be stored in SortedSet
SortedSet<Obj> set = new TreeSet<Obj> ();

Performing Different Operations on SortedSet

1. Adding Elements

 To add elements to a SortedSet, use the add() method.In a TreeSet, elements are automatically sorted in ascending order, duplicates are ignored, and null values are not allowed.

Example:

Java
import java.util.*;

class Geeks {

    public static void main(String[] args) 
    {
        SortedSet<String> ts = new TreeSet<String>();

        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");

        System.out.println(ts);
    }
}

Output
[A, B, C]

2. Accessing the Elements

After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains()first()last(), etc.

Example:

Java
import java.util.*;
class Geeks {

    public static void main(String[] args)
    {
        SortedSet<String> ts = new TreeSet<String>();

        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");

        System.out.println("Sorted Set is: " + ts);

        String check = "D";

        // Check if the above string exists in the SortedSet or not
        System.out.println("Contains: " + check + " " 
                           + ts.contains(check));

        // Print the first element in the SortedSet
        System.out.println("First Value: " + ts.first());

        // Print the last element in the SortedSet
        System.out.println("Last Value: " + ts.last());
    }
}

Output
Sorted Set is: [A, B, C]
Contains: D false
First Value: A
Last Value: C

3. Removing the Values

The values can be removed from the SortedSet using the remove() method.

Example:

Java
import java.util.*;
class Geeks {

    public static void main(String[] args)
    {
        SortedSet<String> ts = new TreeSet<String>();

        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("B");
        ts.add("D");
        ts.add("E");

        System.out.println("Initial TreeSet: " + ts);

        // Removing the element b
        ts.remove("B");

        System.out.println("After removing element: " + ts);
    }
}

Output
Initial TreeSet: [A, B, C, D, E]
After removing element: [A, C, D, E]

4. Iterating through the SortedSet

There are various ways to iterate through the SortedSet. The most famous one is to use the enhanced for loop.

Example:

Java
import java.util.*;
class Geeks
 { 
    public static void main(String[] args)
    {
        SortedSet<String> ts
            = new TreeSet<String>();
 
        // Elements are added using add() method
        ts.add("C");
        ts.add("D");
        ts.add("E");
        ts.add("A");
        ts.add("B");
        ts.add("Z");
 
        // Iterating though the SortedSet
        for (String value : ts)
            System.out.print(value
                             + ", ");
        System.out.println();
    }
}

Output
A, B, C, D, E, Z, 

Note: The class which implements the SortedSet interface is TreeSet.

Example: Java program to demonstrate the creation of SortedSet object using the TreeSet class.

Java
import java.util.*;

class Geeks {

    public static void main(String[] args)
    {
        SortedSet<String> ts
            = new TreeSet<String>();

        // Adding elements into the TreeSet using add()
        ts.add("India");
        ts.add("Australia");
        ts.add("South Africa");

        // Adding the duplicate element
        ts.add("India");

        // Displaying the TreeSet
        System.out.println(ts);

        // Removing items from TreeSet using remove()
        ts.remove("Australia");
        System.out.println("Set after removing: "
                           + "Australia:" + ts);

        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator<String> i = ts.iterator();
        while (i.hasNext())
            System.out.println(i.next());
    }
}

Output
[Australia, India, South Africa]
Set after removing: Australia:[India, South Africa]
Iterating over set:
India
South Africa

Methods of SortedSet Interface

The following are the methods present in the SortedSet interface. Here, the “*” represents that the methods are part of the Set interface.

MethodDescription
*add(element)Adds an element if not already present.
*addAll(collection)Adds all elements from another collection.
*clear()Removes all elements (set remains empty).
comparator()This method returns the comparator used to order the elements in this set.
*contains(element)This method is used to check whether a specific element is present in the Set or not.
*containsAll(collection)Checks if all elements of a collection are in the set.
first()This method returns the first(lowest) element present in this set.
hashCode() Returns the hash code of the set.
headSet(element)This method returns the elements which are less than the element that are present in the sorted set.
*isEmpty()This method is used to check if a SortedSet is empty or not.
last()This method returns the last(highest) element present in the set.
*remove(element)Removes the given element
*removeAll(collection)Removes all matching elements from the set.
*retainAll(collection)Keeps only elements present in the given collection.
*size()Returns the number of elements in the set.
subSet(element1, element2)This method returns a sorted subset from the set containing the elements between element1 and element2.
tailSet(element)This method returns the elements which are greater than or equal to the element that are present in the sorted set.
*toArray()This method is used to form an array of the same elements as that of the Set.

Practice Tags :

Similar Reads