NavigableSet in Java 6.0

NavigableSet API is included in the SCJP 6.0 certification exam. This article explains few important methods with simple example program. NavigableSet is the subinterface of SortedSet. This interface defines methods for finding the element in a list. For example lower() method used for finding the element which is less than the given value. Look into the following example:

package NavigableTutorial.net;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetTutorial1 {
    public static void main(String args[]){
        List list = new ArrayList();
        list.add(3);
        list.add(4);
        list.add(1);
        list.add(8);
        list.add(7);
        list.add(10);
       
        NavigableSet navigableSet = new TreeSet(list);
        System.out.println(navigableSet.lower(8));
        System.out.println(navigableSet.higher(8));
       
    }
}


Output:
7
10

In the above code, NavigableSet.lower() method is used for reteriving the value which is less than '8' in the list. Same way NavigableSet.higher() is used for reteriving the value greater than '8' in the list.

Java 6 - NavigableSet -headSet and tailSet Example Java Collections Framework

The below example explains the headSet and tailSet methods of the NavigableSet.

package examples;

import java.util.NavigableSet;
import java.util.TreeSet;
public class NavigableSetExample {

public static void main(String[] args) {
NavigableSet set = new TreeSet();
// Add elements in to the Navigable Set
set.add(1);
set.add(2);
set.add(3);
System.out.println(set);

// Head Set
System.out.println("Head Set :" + set.headSet(2));
System.out.println("Head Set including given integer: "+ set.headSet(2, true));

// Tail Set
System.out.println("Tail Set" + set.tailSet(2));
System.out.println("Tail Set including given integer: " + set.tailSet(2, false));
}

}

[1, 2, 3]
Head Set :[1]
Head Set including given integer: [1, 2]
Tail Set[2, 3]
Tail Set including given integer: [3]