What is the SortedSet in Java?

In this shot, we will learn about the SortedSet in Java.

Introduction

The SortedSet is present in the SortedSet interface, which extends the Set interface inside the java.util package. It implements a mathematical set. It has all the properties of the Set by extending it, and it also adds a feature with those properties of storing the elements in a sorted manner. The SortedSet interface is implemented by the TreeSet class.

The SortedSet is useful when we want to store the sorted elements and perform some operations over them with the help of supporting methods.

Syntax

The syntax to create a SortedSet is shown below:

SortedSet<dataType> name = new TreeSet<dataType>();

Code

Let’s have a look at the code and see how the SortedSet can be implemented in Java.

import java.util.SortedSet;
import java.util.TreeSet;
class Main
{
public static void main(String args[])
{
SortedSet<Integer> set = new TreeSet<Integer>();
set.add(1);
set.add(8);
set.add(5);
set.add(3);
set.add(0);
set.add(22);
set.add(10);
System.out.println("SortedSet: " + set);
}
}

Explanation:

  • In lines 1 and 2, we imported the required packages.

  • In line 4 we made a Main class.

  • In line 6, we made a main() function.

  • In line 8, we created a SortedSet of the Integer type which is implemented by the TreeSet class.

  • From lines 10 to 16, we added the elements into the SortedSet by using the SortedSet.add() method.

  • In line 17, we displayed the original SortedSet with a message. You can note that even though the order of insertion was different, the elements are stored in a sorted manner in the SortedSet.

So, this is how to create and display the SortedSet in Java.

Free Resources