SortedSet Interface in Java with Examples

26 Jun, 2020
The SortedSet interface 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 to be stored in a sorted manner.
In the above image, the navigable set extends the sorted set interface. Since a set doesn’t 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. Therefore, this interface provides us with a way to navigate through this tree.
Declaration: The SortedSet interface is declared as:
public interface SortedSet extends Set
Example of a Sorted Set:
// Java program to demonstrate the// Sorted Setimport java.util.*;  class SortedSetExample{      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());    }}
[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
Since SortedSet is an interface, 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 SortedSetSortedSet<Obj> set = new TreeSet<Obj> ();
Since SortedSet is an interface, 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: In order to add an element to the SortedSet, we can use the add() method. However, 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 code to demonstrate// the working of SortedSetimport java.util.*;  class GFG {      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);    }}
[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 code to demonstrate// the working of SortedSet  import java.util.*;class GFG {      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());    }}
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 code to demonstrate// the working of SortedSet  import java.util.*;class GFG{      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);    }}
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 code to demonstrate// the working of SortedSet   import java.util.*;class GFG {     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();    }}
A, B, C, D, E, Z,

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 program to demonstrate the// creation of SortedSet object using// the TreeSet class  import java.util.*;  class GFG {      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());    }}
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

The following are the methods present in the SortedSet interface. Here, the “*” represents that the methods are part of the Set interface.
yifan
KaashyapMSK
Java-Collections
Java-SortedSet
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initializing a List in Java
Initialize an ArrayList in Java
Generics in Java
Java Programming Examples