SortedSet Interface In Java Collection Framework

SortedSet Interface is the child interface of Set Interface. If we want to represent a group of individual object as a single entity where duplicated are not allowed and insertion order is not preserved but according to some sorting order then we should go for SortedSet. For Example – Store Employee according to employee email id or store Students according to there enrollment number.

SortedSet Interface has its implementation class TreeSet.

SortedSet interface declaration in Java as per doc:

We can apply below methods on SortedSet implements class objects, that is on the TreeSet object.

Methods & Description

              Methods                                                       Description
Comparator<? super E> compare() Returns the comparator object that describe underline sorting technique used to order the elements in this set, or null if this set uses the default natural sorting order (DNSO) of its elements.

DNSO for Integer -> Ascending

DNSO for String -> Ascending according to alphabetical order

default Spliterator<E> spliterator() Creates a Spliterator over the elements in this sorted set.
E first() Returns the first (lowest) element currently in this set.
E last() Returns the last (highest) element currently in this set.
SortedSet<E> headSet(E toElement) Returns a view of the portion of this set whose elements are strictly less than toElement.
SortedSet<E> subSet(E fromElement, E toElement)  Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
SortedSet<E> tailSet(E fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement.



Following is an example to explain SortedSet functionality.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.