The Wayback Machine - https://web.archive.org/web/20240917151637/https://www.geeksforgeeks.org/sortedset-java-examples/
Open In App

SortedSet Interface in Java with Examples

Last Updated : 03 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let us start with a simple Java code snippet demonstrating creating a SortedSet Interface in Java.

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

public class SortedSetCreation {
    public static void main(String args[]) {
        
        // Create a SortedSet of Strings
        SortedSet<String> sortedSet = new TreeSet<>();
        
        // here, we can perform different operations in SortedSet
        
        // Displaying the SortedSet
        System.out.println("SortedSet elements: " + sortedSet);
    }
}

Output
SortedSet elements: []

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 to be stored in a sorted manner.


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. 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
// Java program to demonstrate the
// Sorted Set
import 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());
    }
}

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

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 SortedSet
SortedSet<Obj> set = new TreeSet<Obj> ();


Performing Various Operations on SortedSet

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

// 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(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 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());
    }
}

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 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);
    }
}

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 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();
    }
}

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 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());
    }
}

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.


Similar Reads

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) Where E is the type of element maintained by this Se
2 min read
SortedSet equals() method in Java with Examples
The equals() method of java.util.SortedSet class is used to verify the equality of an Object with a SortedSet and compare them. The method returns true if the size of both the SortedSets are equal and both contain the same elements. Syntax: public boolean equals(Object o) Parameters: This method takes the object o as a parameter to be compared for
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 added to the set. Return Value: The method returns t
2 min read
SortedSet isEmpty() method in Java with Examples
The java.util.SortedSet.isEmpty() method is used to check if a SortedSet is empty or not. It returns True if the SortedSet is empty otherwise it returns False. Syntax: boolean isEmpty() Parameters: This method does not take any parameter. Return Value: The method returns True if the SortedSet is empty else returns False. Note: The isEmpty() method
1 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 does not take any parameter Return Value: The method
1 min read
SortedSet removeAll() method in Java with Examples
The removeAll() method of SortedSet interface is used to remove from this SortedSet all of its elements that are contained in the specified collection.Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be removed from this SortedSet.Returns Value: This method returns true
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 element that needs to be tested if it is present in
2 min read
SortedSet iterator() method in Java with Examples
The java.util.SortedSet.iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set. Syntax: Iterator iterate_value = sortedSetInstance.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the elements of t
1 min read
SortedSet remove() method in Java with Examples
The remove(Object O) method of SortedSet interface is used to remove a particular element from this SortedSet. Syntax: boolean remove(Object O) Parameters: The parameter O is of the type of element maintained by this SortedSet and specifies the element to be removed from the Set. Return Value: This method returns True if the specified element is pr
1 min read
SortedSet toArray() method in Java with Examples
The toArray() method of Java SortedSet is used to form an array of the same elements as that of the SortedSet. Basically, it copies all the element from a SortedSet to a new array. Syntax: Object[] toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array containing the elements similar to the SortedSe
2 min read
SortedSet size() method in Java with Examples
The size() method of SortedSet interface is used to get the size of the SortedSet or the number of elements present in the SortedSet. Syntax: int size() Parameters: This method does not takes any parameter. Return Value: The method returns the size or the number of elements present in the SortedSet. Note: The size() method in SortedSet is inherited
1 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 is a Collection. This parameter refers to the set
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 returns an integer value which is the hashCode val
2 min read
SortedSet retainAll() method in Java with Examples
The retainAll() method of SortedSet interface is used to retain from this SortedSet, all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this SortedSet. Return Value: This method returns tr
3 min read
Why to Use Comparator Interface Rather than Comparable Interface in Java?
In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object. Here are some reasons why you might want to use the Comparator i
8 min read
SortedSet subSet() method in Java
The subSet() method of SortedSet interface in Java is used to return a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. 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 set returned by this method supports al
2 min read
SortedSet tailSet() method in Java
The tailSet() method of SortedSet interface in Java is used to return a view of the portion of this set whose elements are greater than or equal to the parameter fromElement. 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 set returned by this method supports all o
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 set returned by this method supports all optional
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 lowest element currently in the set.Exceptions: It th
2 min read
SortedSet last() method in Java
The last() method of SortedSet interface in Java is used to return the last i.e., the highest element currently in this set.Syntax: E last() Where, E is the type of element maintained by this Set.Parameters: This function does not accepts any parameter.Return Value: It returns the last or the highest element currently in the set.Exceptions: It thro
2 min read
Difference Between TreeSet and SortedSet in Java
TreeSet is one of the implementations of the Navigable sub-interface. It is underlying data structure is a red-black tree. The elements are stored in ascending order and more methods are available in TreeSet compare to SortedSet. We can also change the sorting parameter using a Comparator. For example, Comparator provided at set creation time, depe
3 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate&lt;T, V&gt; interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate&lt;T, V&gt; Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
Hibernate - SortedSet Mapping
SortedSet can be viewed in a group of elements and they do not have a duplicate element and ascending order is maintained in its elements. By using &lt;set&gt; elements we can use them and the entity should have a Sortedset of values. As an example, we can have a freelancer who works for multiple companies on a shift basis. Here also the one-to-man
6 min read
ToLongFunction Interface in Java with Examples
The ToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces a long-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the input
1 min read
LongToIntFunction Interface in Java with Examples
The LongToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a long-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to define its
1 min read
Practice Tags :