Topics Index

Collections Framework > Collection Interface >
Siva Nookala - 20 Feb 2017
The SortedSet interface extends Set Interface In Java and declares the behaviour of a set sorted in ascending order.

In addition to those methods defined by Set, the SortedSet interface includes these methods,
Comparator comparator()Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
Object first()Returns the first (lowest) element currently in this set.
SortedSet headSet(Object end)Returns a view of the portion of this set whose elements are strictly less than toElement.
Object last()Returns the last (highest) element currently in this set.
SortedSet subSet(Object start, Object end)Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
SortedSet tailSet(Object start)Returns a view of the portion of this set whose elements are greater than or equal to fromElement.

Sorted Set
import java.util.*;

class SortedSetTest
    public static void main(String arg[])
        SortedSet<Integer> ss = new TreeSet<Integer>();
        ss.add(10); // duplicate value
        System.out.println("SortedSet elements : " + ss);
        System.out.print("Iterating SortedSet elements : ");
        Iterator it = ss.iterator();
        while (it.hasNext()) {
            System.out.print( + " ");
        System.out.println("Lowest element : " + ss.first());
        System.out.println("Highest element : " + ss.last());
        System.out.println("Lesser than elements : " + ss.headSet(80));
        System.out.println("Higher than or equals elements : " + ss.tailSet(80));
        System.out.println("Range elements : " + ss.subSet(20, 90));

SortedSet elements : [10, 30, 80, 98, 99]
Iterating SortedSet elements : 10 30 80 98 99
Lowest element : 10
Highest element : 99
Lesser than elements : [10, 30]
Higher than or equals elements : [80, 98, 99]
Range elements : [30, 80]


In this program, a TreeSet is assigned to SortedSet object, six elements are added to it in which one is duplicate and then SortedSet methods like first, headSet, last, subSet and tailSet are applied. It stores the unique elements in ascending order.

  • Add 88 to the SortedSet and see the output is in ascending order or not.
  • You can obtain a set from the sortedSet by using headSet, tailSet and subSet methods. Try with replacing 80 by 30 in tailSet method.
  • Create a new sortedSet for String names and see the names are showing in ascending order or not.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App