Menu
Topics Index
...
`

Navigable Set - Java Example Program


Navigable Set
import java.util.*;

class NavigableSetTest
{
    public static void main(String arg[])
    {
        NavigableSet<Float> ns=new TreeSet<Float>();
        ns.add(10.0f);
        ns.add(10.1f);
        ns.add(10.2f);
        ns.add(10.3f);
        ns.add(10.4f);
        ns.add(10.5f);
                
        System.out.println("Navigable Set elements : " + ns);
        System.out.print("Iterating Navigable set elements : ");
        Iterator it = ns.descendingIterator(); // Descending Iterator
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();
                
        System.out.println("Higher or equal element : " + ns.ceiling(10f));
        System.out.println("The Descending Set : " + ns.descendingSet());
        System.out.println("Lower or equal element : " + ns.floor(10.3f));
        System.out.println("Headset elements : " + ns.headSet(10.3f, false));
        System.out.println("Higher element : " + ns.higher(10.3f));
        System.out.println("Lower element : "+ns.lower(10.3f));
        System.out.println("Deletes lowest element : "+ns.pollFirst());
        System.out.println("Deletes highest element : "+ns.pollLast());    
    }
}
OUTPUT

Navigable Set elements : [10.0, 10.1, 10.2, 10.3, 10.4, 10.5]
Iterating Navigable set elements : 10.5 10.4 10.3 10.2 10.1 10.0
Higher or equal element : 10.0
The Descending Set : [10.5, 10.4, 10.3, 10.2, 10.1, 10.0]
Lower or equal element : 10.3
Headset elements : [10.0, 10.1, 10.2]
Higher element : 10.4
Lower element : 10.2
Deletes lowest element : 10.0
Deletes highest element : 10.5

DESCRIPTION

In this program, a TreeSet is assigned to NavigableSet object, six elements are added to it and then NavigableSet methods like descendingIterator, ceiling, descendingSet, floor, headSet, higher, lower, pollFirst and pollLast are applied.

THINGS TO TRY
  • Replace 10f by 10.3f in ceiling method and see the output, which takes just higher or equal element in set.
  • Replace false by true in headSet method and see the output, which includes the value of head.
  • Create a new Integer NavigableSet and apply all these methods.

© meritcampus 2019

All Rights Reserved.

Open In App