Menu
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,
MethodDescription
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);
        ss.add(30);
        ss.add(98);
        ss.add(80);
        ss.add(10); // duplicate value
        ss.add(99);
        
        System.out.println("SortedSet elements : " + ss);
        System.out.print("Iterating SortedSet elements : ");
        Iterator it = ss.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();
        
        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));
    
    }
}
OUTPUT

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]

DESCRIPTION

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.

THINGS TO TRY
  • 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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.