Java – Navigable Set
Sets:
A Set is a collection that contains no duplicate elements. Sets are collections where no two elements are the same, which means that element1.equals(element2) should never return true. Also at most one element in a set can be null and no more.
A Set. Duplicates are not allowed and at most one null element is allowed
Sorted Sets:
A SortedSet is a set which sorts and maintains the ordering of its elements. Elements will be ordered by their natural ordering or by the use of a Comparator (if the developer provides one). A Comparable interface can help define the ordering for elements. For example a String’s natural ordering will dictate that elements be ordered this way “a”, “b”, “c” etc. The way in which elements are ordered in a Sorted data structure can be redefined by using the Comparator interface.
Sorted set where elements are sorted by natural order.
Navigable set:
A navigable set is a sorted set. Technically this means that a NavigableSet extends from a SortedSet. The navigable set has a couple of methods that will return the closest matching element given a search target. A NavigableSet can be accessed in the ascending or descending order. To get an ascending view of this structure the iterator() method can be used like in all Collection classes. To get a descending view of this structure use the descendingIterator() method. This method returns an Iterator whose elements are in the reverse natural order. That.s a fancy way of saying .in descending order.
The implementations of NavigableSet are the TreeSet and the ConcurrentSkipListSet. Let us take an example of the Iteration orders of the navigable set
Code:
public static void main(String[] args) { NavigableSet <Integer> navigableSet = new TreeSet<Integer>(); navigableSet.add(10); navigableSet.add(20); navigableSet.add(-10); navigableSet.add(40); navigableSet.add(90); Iterator< Integer> iterator = navigableSet.iterator(); Iterator< Integer> reverseIterator = navigableSet.descendingIterator(); System.out.println("Forward ahoy !"); while (iterator.hasNext()) { System.out.println(iterator.next()); } System.out.println(); System.out.println("Reverse yoha !"); while (reverseIterator.hasNext()) { System.out.println(reverseIterator.next()); } }
Output:
The output of this program would be: Forward ahoy ! -10 10 20 40 90 Reverse yoha ! 90 40 20 10 -10
As expected the Iterators iterate through the set in the natural and reverse natural order. Tree sets also automatically sort their elements. There are some key methods that make the NavigableSet useful in certain scenarios. We will have a look at them now.
Key methods in the NavigableSet:
Don’t worry if some of these methods do not make sense. We will take a look at them with an example
| Method name | What element will It return ? |
| lower(element) | Less than current element |
| floor(element) | Less than or equal to current element |
| ceiling(element) | Greater than or equal to current element |
| higher(element) | Greater than current element |
| subSet(fromElem,isInclusive ,toElem, isInclusive) | Returns a subset of the Set from an element to another. Flags can be set to mention if the elements should be inclusive or not |
| headSet(toElem,isInclusive) | A subset of this set whose elements are strictly less than toElem |
| tailSet(fromElem,isInclusive) | A subset of this set whose elements are greater than toElem |
| descendingSet() | Returns a set whose elements are in the descending order |
| pollFirst() | Retrieve and remove the first element |
| pollLast() | Retrieve and remove the last element |
A small program illustrates each method. Assume that a NavigableSet is inserted with the following data just like before.
Values added into the set in this order:
Let’s say the following lines were executed in the program
System.out.println(navigableSet.floor(5)); System.out.println(navigableSet.ceiling(5)); System.out.println(navigableSet.lower(30)); System.out.println(navigableSet.higher(30)); System.out.println(navigableSet.higher(90));
The output would be as follows:
-10 10 20 40 Null
To explain the output, let’s arrange the elements first, the way a sorted set would see them
When the Set encounters methods like floor(),ceiling() etc, this is what it translates to.
floor(5) – Give me the element that is less than or equal to 5. Result is -10
ceiling(5) - Give me the element that is greater than or equal to 5. Result is 10
lower(30) - Give me the element that is less than 30. Result is 20
higher(30) - Give me the element that is greater than 30. Result is 40
Any request for an element that does not match the criteria will result in a null return. For example a request to the set to return something higher than 90 gives null since 90 is the highest value in the set.
More examples:
System.out.println(navigableSet.subSet(10,true,40,true)); System.out.println(navigableSet.tailSet(-10, false)); System.out.println(navigableSet.headSet(40, true)); System.out.println(navigableSet.descendingSet());
The output:
[10, 20, 40] [10, 20, 40, 90] [-10, 10, 20, 40] [90, 40, 20, 10, -10]
Again, given the sorted set this result can be explained.
subSet(10,true,40,true)- Give me all the elements between 10 and 40, inclusive of 10 and 40.
tailSet(-10, false) - Give me all the elements after -10, exclusive of -10.
headSet(40, true)- Give me all the elements before 40, inclusive of 40.
descendingSet()- Show me the Navigable set in descending order
The descending set is nothing but the set in reverse order. It is helpful if you need the entire set in descending order instead of a descending Iterator to the set. That laves us with pollFirst() and pollLast().
Polling through navigable sets:
System.out.println(navigableSet); System.out.println(navigableSet.pollFirst()); System.out.println(navigableSet.pollLast()); System.out.println(navigableSet);
Output:
[-10, 10, 20, 40, 90] -10 90 [10, 20, 40]
The pollFirst() method retrieves and removes the first value in the set. Which is -10. The pollLast() method retrieves and removes the last value in the set, which is 90. As a result the set.s final size is reduced by 2. After removal of -10 and 90 from the set, the final set looks like this [10, 20, 40].
The NavigableMap API is very similar to that of the NavigableSet (It is unfair to compare a Map and Set, but you get the picture). Now that you know how to use a NavigableSet, learning the NavigableMap should easy.
Thanks for this post!
@Monu
Always welcome
nice example with pics. Great job. You spent more time to create pics. This is very easiest way to keep in mind. Thank u ….. Keep it up
Cool Stuff.
Real good article, God bless!!
Awesome… One of the best example. Thanks
@Dhirendra
@Ashish
@tanzy
@balamurugan
You are welcome. Thanks for leaving a comment
Great stuff! thx
thanx alot dear.gud article
Really good article… and pic makes easy to remember
Nice tutorial.
Very nicely explained. Helped me a great deal in understanding this topic. Thanks a lot for your help.
@javee
@chetan
@Rangabhasyam N
@Sahil
@sidsaras
Glad to be of help
Great Article with great explaination!
The first thing I learnt about Java 6.0!
you rule dude
Buddy,
Thanks a lot for you effort and indeed it was really a nice one.
Excellent write-up…Thanks a lot for the wonderful explanation with pictures !!
Nice article.! It’ll surely help me.
Thanks for this post. One of the best example…
Very good help on NavigableSet and its methods.
Pictures make it crystal clear. Cannot forget the
excellent picture-examples. Thankyou !
Really cool! btw.. which scenarios will this feature be helpful?
Great stuff!
clear and lucid explanation. thanks for your help!