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
Mainclass. -
In line 6, we made a
main()function. -
In line 8, we created a
SortedSetof theIntegertype which is implemented by theTreeSetclass. -
From lines 10 to 16, we added the elements into the
SortedSetby using theSortedSet.add()method. -
In line 17, we displayed the original
SortedSetwith a message. You can note that even though the order of insertion was different, the elements are stored in a sorted manner in theSortedSet.
So, this is how to create and display the SortedSet in Java.