Table of contents
1.
Introduction
2.
What is SortedSet Interface in Java?
3.
Java SortedSet sorting order
4.
Methods for Java SortedSet Interface
5.
How to Create SortedSet Objects in Java?
6.
Properties of Java SortedSet Interface
7.
Difference between HashSet and TreeSet
8.
Frequently Asked Questions
8.1.
What other operations does SortedSet provide over Set?
8.2.
How do TreeSet and SortedSet connect? 
8.3.
How do NavigableSets and SortedSets differ in Java?
8.4.
Do sorted sets duplicate?
9.
Conclusion
Last Updated: Apr 7, 2025
Easy

SortedSet in Java

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

Introduction

The SortedSet interface in Java is part of the Collection Framework and ensures elements are stored in a sorted order. Unlike regular sets, SortedSet maintains a defined sequence, which is crucial for cases where element order is important. Let's explore its functionality and usage.

Let's say we have three sets: Set_1=[2, 3, 5], Set_2=[3, 2, 5], and Set_3=[2, 5, 3]. 

Can we say that these three sets are equal in any way?

The answer is yes because all the elements are present in all three sets, and the order of the elements does not necessarily need to be equal. 

But these three sets won't be equal with a Sorted set since the order of the other two sets is not maintained. Let's have a closer look at the SortedSet to understand this concept.

What is SortedSet Interface in Java?

SortedSet is an interface in the Java.util package and extends the Set interface of the Collection Framework. SortedSet extends Set.

SortedSet should be used in cases where no duplicates are allowed and we want to group objects according to some Sorting order.

We must use the collection method when dealing with a Set since Sets do not contain any new methods. 

According to the SortedSet hierarchy:

Java SortedSet sorting order

SortedSets in Java use the natural sorting order of their elements as the default sorting order. java.lang.The elements must implement comparable for the SortedSet to determine their natural order.

The elements are not naturally ordered if they don't implement the Comparable interface. A Comparator implementation must be passed to the SortedSet when it is created in that case. It is also possible to construct TreeSet with a Comparator. A Java TreeSet with a Comparator can be created as follows:

Comparator comparator = new MyComparator();
SortedSet ss = new TreeSet(comparator);

Interface in Java

Methods for Java SortedSet Interface

There are about six methods that are explicitly used for sorted sets:

Methods

Description

first()The first element in a Set can be identified using this method.
last()The group first element in a Set can be identified using this method.
headset(element)It allows us to find the elements in a set that are less than a specific element.
tailSet(element)We can identify which elements in the Set are greater than a specific element.
subSet(element_1, element_2)The elements less than element_2 and greater than element_1 is to be known.
comparator()The term is used to describe the sorting technique. By default, it will return null when using the default sorting method.

How to Create SortedSet Objects in Java?

The SortedSet type is an interface and cannot be used to create objects. For an object to be created, we must extend the Set. An implementation of this interface is TreeSet.

TreeSet: Collections framework has a TreeSet class that implements a sorted interface, and sorted extends Set interface.

Here is the implementation of Sortedset by using the methods we have mentioned above:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        SortedSet < Integer > ss = new TreeSet < Integer > ();

        // Adding elements to set using add()
        ss.add(23);
        ss.add(54);
        ss.add(12);
        ss.add(9);

        //Printing the SortedSet
        System.out.println("Sorted Set: " + ss);

        // Printing the first element in the SortedSet
        System.out.println("First element is: " + ss.first());

        // Printing the first element in the SortedSet
        System.out.println("Last element  is: " + ss.last());

        // Printing the elements which are less than 20 in the SortedSet
        System.out.println("Elements less than 20: " + ss.headSet(20));

        // Printing the elements which are greater than 20 in the SortedSet
        System.out.println("Elements greater than 20: " + ss.tailSet(20));

        // Printing the elements between 13 and 70 in the SortedSet
        System.out.println("Elements greater than 10 and less than 70: " +
            ss.subSet(10, 70));

        // Printing the elements between 13 and 70 in the SortedSet
        System.out.println("Underlying sorting algorithm is: " +
            ss.comparator());
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Sorted Set: [9, 12, 23, 54]
First element is: 9
Last element  is: 54
Elements less than 20: [9, 12]
Elements greater than 20: [23, 54]
Elements greater than 10 and less than 70: [12, 23, 54]
Underlying sorting algorithm is: null
You can also try this code with Online Java Compiler
Run Code

 

Practice it on online java compiler for better understanding.

Properties of Java SortedSet Interface

  • It is not possible to have a null element in a SortedSet. A NullPointerException occurs at runtime if you attempt to insert a null element.
  • The elements of a SortedSet can't be duplicated since it is a set.
  • Comparisons are used to sort SortedSet elements. By default, elements in a SortedSet will be sorted in ascending order if no Comparator is specified.
  • A Comparable type must be inserted, and the elements must be Comparable to each other.
  • There is a method of retrieving the first and the last element of a SortedSet. SortedSet elements cannot be accessed randomly.
  • A sorted set is just a view of the original set returned by headSet(), tailSet(), and subSet() methods. Therefore, changes in the returned Set reflect changes in the original Set.

Difference between HashSet and TreeSet

FeatureHashSetTreeSet
Underlying Data StructureHashMapTreeMap (Red-Black Tree)
Order of ElementsNo guaranteed orderElements are sorted (natural order or by comparator)
Time Complexity (Add)O(1) average, O(n) worst-caseO(log n)
Time Complexity (Remove)O(1) average, O(n) worst-caseO(log n)
Time Complexity (Contains)O(1) average, O(n) worst-caseO(log n)
Allows Null ValuesYes (only one null element allowed)No (throws NullPointerException if null is added)
PerformanceFaster for unordered operationsSlower due to sorting overhead
Use CaseQuick access when order doesn't matterWhen sorted data is needed
ImplementsSet interfaceNavigableSet interface

Frequently Asked Questions

What other operations does SortedSet provide over Set?

The SortedSet is a Set in which its elements are ordered ascendingly, either following their natural order or according to a Comparator given at creation. Apart from the standard Set operations, the SortedSet interface allows operations such as Range view, Endpoints, and Compare access.

How do TreeSet and SortedSet connect? 

There is an interface called SortedSet. It maintains a list of ordered elements, and there is an implementation of SortedSet called TreeSet.

How do NavigableSets and SortedSets differ in Java?

The NavigableSet interface derives from the SortedSet interface. The sorting and navigation methods are the same as those found in a SortedSet, except that navigation methods are also available.

Do sorted sets duplicate?

Duplicates are not accepted by the SortedSet<T> class. A reference to an item that already exists in the Set will result in this method returning false and not throwing an exception.

Conclusion

This article has provided an overview of SortedSet within Java's Collection Framework, discussing its key features and methods. From enforcing order without duplicates to handling comparisons, SortedSet is a powerful tool for organizing data efficiently. Practice the examples to deepen your understanding and improve your coding skills.

Recommended Problems - 


We hope that this blog has helped you enhance your knowledge about SortedSet and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. 

Live masterclass