Java SortedSet<E> Interface

Last Updated : 7 Aug 2026

In Java, the he java.util.SortedSet<E> interface is part of the Java Collections Framework. It extends the Set<E> interface. It provides a collection of unique elements, where the elements are stored in sorted order.

A set is used to provide a particular ordering on its element. The elements are ordered either by using a natural ordering or by using a Comparator. All the elements which are inserted into a sorted set must implement the Comparable interface.

The SortedSet<E> interface is a subtype of the Set<E> interface, which means that it inherits all of its methods and adds additional functionality related to sorting. Being a set, it does not allow duplicate elements, and its elements are maintained in sorted order. The set's iterator traverses the set in an ascending order. Several other operations are provided in order to make best use of ordering. All the elements must be mutually comparable.

SortedSet Interface Methods

MethodsDescription
comparator()Returns the comparator which is used to order the elements in the given set. Also returns null if the given set uses the natural ordering of the element.
first()Returns the first element from the current set.
headSet(E toElement)Returns a view of the portion of the given set whose elements are strictly less than the toElement.
last()Returns the reverse order view of the mapping which present in the map.
spliterator()Returns a key-value mapping which is associated with the least key in the given map. Also, returns null if the map is empty.
subSet(E fromElement, E toElement)Returns a key-value mapping which is associated with the greatest key which is less than or equal to the given key. Also, returns null if the map is empty.
tailSet(E fromElement)Returns a view of the map whose keys are strictly less than the toKey.

Natural Ordering and Custom Comparators

The natural ordering of elements in a SortedSet<E> is determined by the implementation of the Comparable interface by the elements themselves. If the elements do not implement Comparable, a ClassCastException will be thrown at runtime.

Alternatively, we can specify a custom comparator by providing an instance of the Comparator interface when creating the SortedSet<E>. It allows sorting based on criteria other than the natural ordering of elements.

Implementations of SortedSet<E>

The TreeSet<E> class is the most common implementation of the SortedSet<E> interface. It uses a Red-Black tree data structure to store elements in sorted order, providing guaranteed log(n) time cost for the basic operations like add, remove, and contains.

Use Cases

The SortedSet<E> interface is useful in scenarios where we need to maintain a collection of unique elements in sorted order. Some common use cases include:

  • Maintaining a Dictionary or Glossary: When building applications that involve managing word lists, glossaries, or dictionaries, SortedSet<E> ensures that the terms are stored in alphabetical order, facilitating efficient lookup and retrieval.
  • Implementing a Priority Queue: Priority queues are often used in algorithms where elements need to be processed based on their priority. By storing elements in a SortedSet<E>, we can ensure that the highest priority elements are always at the beginning or end of the set, depending on your requirements.
  • Scheduling Tasks: In applications involving scheduling or task management, SortedSet<E> can be used to maintain a sorted list of tasks based on priority, deadline, or scheduled time. It allows for efficient retrieval of tasks in the order they need to be executed.
  • Maintaining a Leaderboard: When building games or applications with leaderboards, SortedSet<E> can be used to store player scores or rankings in sorted order. It ensures that the leaderboard is always up-to-date and can be quickly accessed to display the top players.
  • Processing Event Streams: In event-driven applications or systems that handle streams of events, SortedSet<E> can be used to maintain a sorted list of events based on their occurrence time or other criteria. It allows for efficient processing of events in chronological or priority order.
  • Generating Reports or Summaries: When generating reports or summaries from large datasets, SortedSet<E> can be used to store unique elements such as categories, tags, or keywords in sorted order. It facilitates efficient aggregation and analysis of data.
  • Implementing Autocomplete or Suggestions: In user interfaces that feature autocomplete or suggestion functionality, SortedSet<E> can be used to store a sorted list of suggestions based on user input. It ensures that the suggestions are displayed in a predictable and ordered manner.
  • Managing Preferences or Settings: In applications where users can customize their preferences or settings, SortedSet<E> can be used to store options or choices in sorted order. It provides a consistent and organized way for users to select their preferences.

Performance Considerations

  • The performance of operations on a SortedSet<E> depends on the underlying implementation. For TreeSet<E>, basic operations like add, remove, and contains have a time complexity of O(log n).
  • When using custom comparators, ensure that they adhere to the requirements of a valid comparison function to maintain the sorted order of elements.

Example

This program demonstrates the SortedSet interface using a TreeSet. It stores unique strings in alphabetical order, retrieves the first and last elements, and creates a subset of elements within a specified range.

Java

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
        SortedSet sortedSet = new TreeSet<>();  
        // Adding elements to the sorted set  
        sortedSet.add("banana");  
        sortedSet.add("apple");  
        sortedSet.add("orange");  
        // Printing the sorted set  
        System.out.println("Sorted Set: " + sortedSet);  
        // Using methods of SortedSet  
        System.out.println("First element: " + sortedSet.first());  
        System.out.println("Last element: " + sortedSet.last());  
        // Creating a subset of the sorted set  
        SortedSet subset = sortedSet.subSet("apple", "orange");  
        System.out.println("Subset: " + subset);  
    }  
}  
Compile and Run

Output:

Sorted Set: [apple, banana, orange]
First element: apple
Last element: orange
Subset: [apple, banana]

Example

This program demonstrates the SortedSet interface using a TreeSet. It stores unique car names in alphabetical order and prints all elements. It also retrieves the first and last elements. The headSet() method gets the elements before a specified value. The tailSet() method gets the elements from a specified value onward.

Java

import java.util.SortedSet;  
import java.util.TreeSet;  
public class Main {  
   public static void main(String[] args) {  
       SortedSet set = new TreeSet();   
            // Add the elements in the given set.  
            set.add("Audi");  
            set.add("BMW");  
            set.add("Mercedes");  
            set.add("Baleno");  
            System.out.println("The list of elements is given as:");  
            for (Object object : set) {  
                System.out.println(object);  
                  }  
            //Returns the first element  
           System.out.println("The first element is given as: " + set.first());     
            //Returns the last element  
           System.out.println("The last element is given as: " + set.last());  
           //Returns a view of the portion of the given set whose elements are strictly less than the toElement.   
           System.out.println("The respective element is given as: " + set.headSet("Baleno"));  
           //Returns a view of the map whose keys are strictly less than the toKey.  
           System.out.println("The respective element is given as: " + set.tailSet("Audi"));  
   }    
}  
Compile and Run

Output:

The list of elements is given as:
Audi
BMW
Baleno
Mercedes
The first element is given as: Audi
The last element is given as: Mercedes
The respective element is given as: [Audi, BMW]
The respective element is given as: [Audi, BMW, Baleno, Mercedes]

This program demonstrates the SortedSet interface using a TreeSet. It stores integers in sorted order and uses methods like first(), last(), headSet(), tailSet(), subSet(), and comparator() to access different parts and properties of the set.

Java

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
        // Creating a sorted set  
        SortedSet<Integer> sortedSet = new TreeSet<>();  
        // Adding elements to the sorted set  
        sortedSet.add(5);  
        sortedSet.add(3);  
        sortedSet.add(8);  
        sortedSet.add(2);  
        sortedSet.add(10);  
        // Printing the sorted set  
        System.out.println("Sorted Set: " + sortedSet);  
        // Using first() method  
        System.out.println("First element: " + sortedSet.first());  
        // Using last() method  
        System.out.println("Last element: " + sortedSet.last());  
        // Using headSet() method  
        SortedSet<Integer> headSet = sortedSet.headSet(5);  
        System.out.println("Head set (less than 5): " + headSet);  
        // Using tailSet() method  
        SortedSet<Integer> tailSet = sortedSet.tailSet(5);  
        System.out.println("Tail set (greater than or equal to 5): " + tailSet);  
        // Using subSet() method  
        SortedSet<Integer> subSet = sortedSet.subSet(3, 8);  
        System.out.println("Subset (from 3 inclusive to 8 exclusive): " + subSet);  
        // Using comparator() method  
        Comparator<? super Integer> comparator = sortedSet.comparator();  
        System.out.println("Comparator used: " + comparator);  
    }  
}  
Compile and Run

Output:

Sorted Set: [2, 3, 5, 8, 10]
First element: 2
Last element: 10
Head set (less than 5): [2, 3]
Tail set (greater than or equal to 5): [5, 8, 10]
Subset (from 3 inclusive to 8 exclusive): [3, 5]
Comparator used: null