Menu
Topics Index
...
`

TreeSetSample - Java Example Program


TreeSetSample
import java.util.*;

class TreeSetSample
{
    public static void main(String arg[])
    {
        TreeSet<Integer> input = new TreeSet<Integer>(); // LINE A
        input.add(1);
        input.add(3);
        input.add(2);
        input.add(6);
        input.add(5);
        input.add(4);
        System.out.println(input); // LINE B
        System.out.println("First Element in Set : " + input.first()); // LINE C
        System.out.println("Last Element in Set : " + input.last()); // LINE D
        System.out.println("Element higher to 4 : " + input.higher(4)); // LINE E
        //higher returns the next higher number to the given number
        System.out.println("Element lower to 3 : " + input.lower(3));
        //lower returns the next lower number to the given number    
    }
}
OUTPUT

[1, 2, 3, 4, 5, 6]
First Element in Set : 1
Last Element in Set : 6
Element higher to 4 : 5
Element lower to 3 : 2

DESCRIPTION

In the above program we demonstrated how TreeSet functions at LINE A we have created an empty TreeSet and added elements to it. At LINE B we are displaying the sorted elements of TreeSet. At LINE C we are getting the first element of the Set using first method. At LINE D we are getting last element of the Set using last method. At LINE E we are displaying the next higher number of 4 in the Set using higher method and at LINE F we are displaying the next lower number of 3 in the Set using lower method.

THINGS TO TRY
  • Now try to get a subset of the above shown set from index 0 to index 4. Use the below sample code.
    TreeSet set = input.subSet(0, 4);
    System.out.println(set);
  • Display the elements which are less than 5 using headSet method. Use the below sample code.
    System.out.println(input.headSet(5));
    The output will be [1, 2, 3, 4] Since the return type of the headSet is SortedSet.
  • Display the elements which are greater than or equal to 2 using tailSet method. Use the below sample code._
    System.out.println(input.tailSet(2));
    The output will be [2, 3, 4, 5, 6]. Since the tailSet method returns a portion of the set whose elements are greater than or equal to given element.

© meritcampus 2019

All Rights Reserved.

Open In App