Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
SortedSet add() method in Java with Examples
Next article icon

SortedSet Interface in Java with Examples

Last Updated : 02 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The SortedSet interface is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this interface in a sorted manner.

Key Features:

  • 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.

Now, let us go through a simple example of the SortedSet interface, and then we will deep dive into the concept.

Example:

Java
// Java Program Implementing SortedSet 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 Diagram of SortedSet in Java

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

SortedSet In Java Collection

In the above image, the navigable set extends the sorted set interface. A set does not retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. So, this interface provides us with a way to navigate through this tree.

Declaration of SortedSet Interface

Syntax:

The SortedSet interface is declared as,

public interface SortedSet extends Set

Example of a Sorted Set

Java
// Java program to demonstrate the // Sorted Set 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 

Note: All the elements of a SortedSet must implement the Comparable interface (or be accepted by the specified Comparator) and all such elements must be mutually comparable. Mutually Comparable simply means that two objects accept each other as the argument to their compareTo method.

Creating SortedSet Objects

SortedSet is an interface, so, objects cannot be created of the type SortedSet. We always need a class which extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the SortedSet. This type-safe set can be defined as:

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

Performing Different Operations on SortedSet

SortedSet is an interface and it can be used only with a class which implements this interface. TreeSet is the class which implements the SortedSet interface. Now, let’s see how to perform a few frequently used operations on the TreeSet.

1. Adding Elements

To add an element to the SortedSet, we can use the add() method. The insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in the ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the SortedSet.

Java
// Java code to demonstrate // the working of SortedSet 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.

Java
// Java Program to demonstrate // the working of SortedSet 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.

Java
// Java code to demonstrate // the working of SortedSet 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.

Java
// Java code to demonstrate // the working of SortedSet 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.

TreeSet

TreeSet class which is implemented in the collections framework is an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it stores elements in a sorted format. TreeSet uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can iterate in descending order using method TreeSet.descendingIterator(). Let’s see how to create a sortedset object using this class.

Java
// Java program to demonstrate the // creation of SortedSet object using // the TreeSet class 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)This method is used to add a specific element to the set. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.
*addAll(collection)This method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
*clear()This method is used to remove all the elements from the set but not delete the set. The reference for the set still exists.
comparator()This method returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
*contains(element)This method is used to check whether a specific element is present in the Set or not.
*containsAll(collection)This method is used to check whether the set contains all the elements present in the given collection or not. This method returns true if the set contains all the elements and returns false if any of the elements are missing.
first()This method returns the first(lowest) element present in this set.
hashCode()This method is used to get the hashCode value for this instance of the Set. It returns an integer value which is the hashCode value for this instance 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)This method is used to remove the given element from the set. This method returns True if the specified element is present in the Set otherwise it returns False.
*removeAll(collection)This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changed as a result of the call.
*retainAll(collection)This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the call.
*size()This method is used to get the size of the set. This returns an integer value which signifies the number of elements.
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.

Next Article
SortedSet add() method in Java with Examples

K

kartik
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java-SortedSet
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    SortedSet Interface in Java with Examples
    The SortedSet interface is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this
    8 min read
    SortedSet add() method in Java with Examples
    The add() method of SortedSet in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set. Syntax: boolean add(E element) Wh
    2 min read
    SortedSet addAll() method in Java with Examples
    The addAll(Collection C) method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order. Syntax: boolean addAll(Collection C) Parameters: The parameter C is a collection of any type that is to be ad
    2 min read
    SortedSet clear() method in Java with Examples
    The clear() method is used to remove all the elements from a SortedSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing Set. Syntax: void clear() Parameters: The method doe
    1 min read
    TreeSet comparator() Method in Java with Examples
    TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to co
    3 min read
    SortedSet contains() method in Java with Examples
    The contains() method is used to check whether a specific element is present in the SortedSet or not. So basically it is used to check if a SortedSet contains any particular element. Syntax: boolean contains(Object element) Parameters: The parameter element is of the type of SortedSet. This is the e
    2 min read
    SortedSet containsAll() method in Java with Examples
    The containsAll() method of Java SortedSet is used to check whether two sets contain the same elements or not. It takes one set as a parameter and returns True if all of the elements of this set is present in the other set. Syntax: public boolean containsAll(Collection C) Parameters: The parameter C
    2 min read
    SortedSet first() method in Java
    The first() method of SortedSet interface in Java is used toReturns the first i.e., the lowest element currently in this set.Syntax: E first() Where, E is the type of element maintained by this Set.Parameters: This function does not accepts any parameter.Return Value: It returns the first or the low
    2 min read
    SortedSet hashCode() method in Java with Examples
    The hashCode() method of SortedSet in Java is used to get the hashCode value for this instance of the SortedSet. It returns an integer value which is the hashCode value for this instance of the SortedSet. Syntax: public int hashCode() Parameters: This function has no parameters. Returns: The method
    2 min read
    SortedSet headSet() method in Java
    The headSet() method of SortedSet interface in Java is used to return a view of the portion of this set whose elements are strictly less than the parameter toElement. The set returned by this method is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences