Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is SortedSet?
3.
SortedSet sorting order
4.
Methods for SortedSet
4.1.
Creating SortedSet Objects
5.
Properties Of SortedSet Interface
6.
Frequently Asked Questions
6.1.
What other operations does SortedSet provide over Set?
6.2.
How do TreeSet and SortedSet connect? 
6.3.
Do sorted sets duplicate?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

SortedSet

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Let's say we have three sets: Set_1=[2, 3, 5], Set_2=[3, 2, 5], and Set_3=[2, 5, 3]. 

Can we say that these three sets are equal in any way?

The answer is yes because all the elements are present in all three sets, and the order of the elements does not necessarily need to be equal. 

But these three sets won't be equal with a Sorted set since the order of the other two sets is not maintained. Let's have a closer look at the SortedSet to understand this concept.

What is SortedSet?

SortedSet is an interface in the Java.util package and extends the Set interface of the Collection Framework. SortedSet extends Set.

SortedSet should be used in cases where no duplicates are allowed and we want to group objects according to some Sorting order.

We must use the collection method when dealing with a Set since Sets do not contain any new methods. 

According to the SortedSet hierarchy:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

SortedSet sorting order

SortedSets in Java use the natural sorting order of their elements as the default sorting order. java.lang.The elements must implement comparable for the SortedSet to determine their natural order.

The elements are not naturally ordered if they don't implement the Comparable interface. A Comparator implementation must be passed to the SortedSet when it is created in that case. It is also possible to construct TreeSet with a Comparator. A Java TreeSet with a Comparator can be created as follows:

Comparator comparator = new MyComparator();
SortedSet ss = new TreeSet(comparator);

Interface in Java

Methods for SortedSet

There are about six methods that are explicitly used for sorted sets:

Methods

Description

first() The first element in a Set can be identified using this method.
last() The group first element in a Set can be identified using this method.
headset(element) It allows us to find the elements in a set that are less than a specific element.
tailSet(element) We can identify which elements in the Set are greater than a specific element.
subSet(element_1, element_2) The elements less than element_2 and greater than element_1 is to be known.
comparator() The term is used to describe the sorting technique. By default, it will return null when using the default sorting method.

Creating SortedSet Objects

The SortedSet type is an interface and cannot be used to create objects. For an object to be created, we must extend the Set. An implementation of this interface is TreeSet.

TreeSet: Collections framework has a TreeSet class that implements a sorted interface, and sorted extends Set interface.

Here is the implementation of Sortedset by using the methods we have mentioned above:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        SortedSet < Integer > ss = new TreeSet < Integer > ();

        // Adding elements to set using add()
        ss.add(23);
        ss.add(54);
        ss.add(12);
        ss.add(9);

        //Printing the SortedSet
        System.out.println("Sorted Set: " + ss);

        // Printing the first element in the SortedSet
        System.out.println("First element is: " + ss.first());

        // Printing the first element in the SortedSet
        System.out.println("Last element  is: " + ss.last());

        // Printing the elements which are less than 20 in the SortedSet
        System.out.println("Elements less than 20: " + ss.headSet(20));

        // Printing the elements which are greater than 20 in the SortedSet
        System.out.println("Elements greater than 20: " + ss.tailSet(20));

        // Printing the elements between 13 and 70 in the SortedSet
        System.out.println("Elements greater than 10 and less than 70: " +
            ss.subSet(10, 70));

        // Printing the elements between 13 and 70 in the SortedSet
        System.out.println("Underlying sorting algorithm is: " +
            ss.comparator());
    }
}

 

Output:

Sorted Set: [9, 12, 23, 54]
First element is: 9
Last element  is: 54
Elements less than 20: [9, 12]
Elements greater than 20: [23, 54]
Elements greater than 10 and less than 70: [12, 23, 54]
Underlying sorting algorithm is: null

 

Practice it on online java compiler for better understanding.

Properties Of SortedSet Interface

  • It is not possible to have a null element in a SortedSet. A NullPointerException occurs at runtime if you attempt to insert a null element.
  • The elements of a SortedSet can't be duplicated since it is a set.
  • Comparisons are used to sort SortedSet elements. By default, elements in a SortedSet will be sorted in ascending order if no Comparator is specified.
  • A Comparable type must be inserted, and the elements must be Comparable to each other.
  • There is a method of retrieving the first and the last element of a SortedSet. SortedSet elements cannot be accessed randomly.
  • A sorted set is just a view of the original set returned by headSet(), tailSet(), and subSet() methods. Therefore, changes in the returned Set reflect changes in the original Set.

Frequently Asked Questions

What other operations does SortedSet provide over Set?

The SortedSet is a Set in which its elements are ordered ascendingly, either following their natural order or according to a Comparator given at creation. Apart from the standard Set operations, the SortedSet interface allows operations such as Range view, Endpoints, and Compare access.
 

How do TreeSet and SortedSet connect? 

There is an interface called SortedSet. It maintains a list of ordered elements, and there is an implementation of SortedSet called TreeSet.
 

How do NavigableSets and SortedSets differ in Java?

The NavigableSet interface derives from the SortedSet interface. The sorting and navigation methods are the same as those found in a SortedSet, except that navigation methods are also available.
 

Do sorted sets duplicate?

Duplicates are not accepted by the SortedSet<T> class. A reference to an item that already exists in the Set will result in this method returning false and not throwing an exception.

Conclusion

In this blog, we have seen what is SortedSet in the Collection Framework and also the methods of SortedSet.

Recommended Problems - 


We hope that this blog has helped you enhance your knowledge about SortedSet and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
TreeSet
Next article
LinkedHashSet
Live masterclass