In the example below we have used NavigableSet
method to sort the elements in ascending order, descending order, also to
retrieve the element which is immediately greater than or equal to 35 etc. With
the help of NavigableSet methods its just a method call to get the result. It is used to
return the closest matches of elements for the given elements in the collection.
Description of program:
Inserting the data in the NavigableSet by the add() method. The NavigableSet provides the facility to getting the data in both orders: ascending and descending orders. The descendingSet() method returns the data from the NavigableSet in descending order. If you want to get the data in ascending order must be used an iterator. An iterator stores the data as a index and the hasNext() method returns 'true' until, the next() method returns the element in ascending order.
Here, you remove the element from the NavigableSet at first and last position, you use the pollFirst() and pollLast() methods. Sometimes, you want to get the less and greater than or equal to the given element by using the floor() and ceiling() methods. For getting the all elements of the NavigableSet that is greater than or equal to the given element by the tailSet() method and less than or equal to the given element of the NavigableSet by the headSet() method.
Here is the code of program:
Output of this program
Navigable set Example!
Ascending order navigable set: 10 20 30 50 80 100
Descending order navigable set: [100, 80, 50, 30, 20, 10]
Least element in Navigable set greater than or equal to 35: 50
Greatest element in Navigable set less than or equal to 35: 30
Navigable set whose elements are strictly less than '40': [10, 20, 30]
Navigable set whose elements are greater than or equal to '40': [50, 80, 100]
Remove element: 10
Now navigable set: [100, 80, 50, 30, 20]
Remove element: 100
Now navigable set: [80, 50, 30, 20]
Posted on: June 22, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles