Menu
Topics Index
...
`

Sorted Set - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App