There are two new interfaces in Java 6 SE called "NavigableMap" and "NavigableSet" which facilitate navigating through collections. NavigableSet extends SortedSet and is implemented by TreeSet and concurrentSkipListSet (a new class in Java collection).

ConcurrentSkipListSet is one of the class that implements NavigableSet and it is used to return the closest matches of elements. It includes methods to return iterators in ascending and descending orders, as well as methods that return a sorted or navigable set for a special portion of data.


 



Example:











package visualbuilder;

import java.util.*;

import java.util.concurrent.*;

public class UseNavigableSet

{

public static void main(String[] args)

{

System.out.println("Example of Navigable Set");

NavigableSet nset = new ConcurrentSkipListSet();

nset.add("20");

nset.add("60");

nset.add("50");

nset.add("40");

nset.add("30");

nset.add("80");

Iterator iterator = nset.iterator(); // Returns an iterator over the elements in navigable set, in ascending order.



System.out.print("In ascending order :");

while (iterator.hasNext())

{ //Ascending order list

System.out.print(iterator.next() + " ");

}

System.out.println(); //Descending order list

System.out.println("In descending order : " + nset.descendingSet() + "\n");

System.out.println("Remove element: " + nset.pollLast());

//After removing the last element, now get navigable set

System.out.println("Now navigable set: " + nset.descendingSet());

}

}









 



Output:







In above example we are inserting the data in the NavigableSet by the "add()" method. The NavigableSet provides the facility for retriving the data in ascending and descending order. The "descendingSet()" method returns the data from the NavigableSet in descending order. If you want to get the data in ascending order then we must use an iterator.

Here in the example, we are removing the element from the NavigableSet at last position, we can use "pollFirst()" method to remove the element from the set at first position and " pollLast()" method to remove element from NavigableSet at last position.

                    

Copyright © 2012 VisualBuilder. All rights reserved