Home > Java certifications > Java – Navigable Set

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.

Back to home

  1. Monu
    August 20th, 2009 at 12:02 | #1

    Thanks for this post!

  2. August 20th, 2009 at 17:36 | #2

    @Monu
    Always welcome :)

  3. balamurugan
    September 1st, 2009 at 13:46 | #3

    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

  4. September 8th, 2009 at 10:15 | #4

    Cool Stuff.

  5. Ashish
    September 12th, 2009 at 22:11 | #5

    Real good article, God bless!!

  6. Dhirendra
    September 24th, 2009 at 15:47 | #6

    Awesome… One of the best example. Thanks

  7. September 24th, 2009 at 16:20 | #7

    @Dhirendra

    @Ashish

    @tanzy

    @balamurugan
    You are welcome. Thanks for leaving a comment

  8. javee
    November 5th, 2009 at 13:35 | #8

    Great stuff! thx

  9. chetan
    November 5th, 2009 at 20:41 | #9

    thanx alot dear.gud article

  10. Rangabhasyam N
    December 4th, 2009 at 12:11 | #10

    Really good article… and pic makes easy to remember

  11. Sahil
    January 5th, 2010 at 01:36 | #11

    Nice tutorial.

  12. sidsaras
    January 26th, 2010 at 18:32 | #12

    Very nicely explained. Helped me a great deal in understanding this topic. Thanks a lot for your help.

  13. January 27th, 2010 at 04:30 | #13
  14. VIKAS BHATT
    February 5th, 2010 at 10:15 | #14

    Great Article with great explaination!
    The first thing I learnt about Java 6.0!
    you rule dude ;)

  15. eyes
    March 29th, 2010 at 08:38 | #15

    Buddy,
    Thanks a lot for you effort and indeed it was really a nice one.

  16. Deepak
    April 20th, 2010 at 09:37 | #16

    Excellent write-up…Thanks a lot for the wonderful explanation with pictures !!

  17. Joseph
    June 16th, 2010 at 08:49 | #17

    Nice article.! It’ll surely help me.

  18. Arnab
    June 23rd, 2010 at 16:54 | #18

    Thanks for this post. One of the best example…

  19. Neha
    July 28th, 2010 at 06:35 | #19

    Very good help on NavigableSet and its methods.
    Pictures make it crystal clear. Cannot forget the
    excellent picture-examples. Thankyou !

  20. ND
    October 27th, 2010 at 12:06 | #20

    Really cool! btw.. which scenarios will this feature be helpful?

  21. Khan
    May 20th, 2011 at 20:45 | #21

    Great stuff!

  22. Aity
    July 11th, 2011 at 17:35 | #22

    clear and lucid explanation. thanks for your help!

  23. January 30th, 2013 at 11:00 | #23

    Very Nice Stuff… thank you very much…

  24. March 27th, 2013 at 06:14 | #24

    Nice post. I learn something new and challenging on websites I stumbleupon every day. It will always be helpful to read through articles from other authors and practice a little something from their websites. toric contact lenses reviews http://cityprotocol.org/wiki/index.php?title=Nonprescription-Colored-Contacts—A-Guide

  25. April 17th, 2013 at 06:58 | #25

    If you could do something you never did before would you?
    I mean writing about Java – Navigable Set – CertPal is
    good but is it a safe subject considering
    your websites is about java? All things considered it is
    a great post however I bet you could try branching into other subjects like stubs marine for example.
    Just an idea… I trust you do not mind me declaring
    that.

  26. March 18th, 2014 at 23:57 | #26

    You need to consult a professional with a PhD or a doctorate.
    I remember it as a humorously weird compliiment social media
    sites for business to the girl of his dreams. You are rushed to the hospital,
    he wrote in an essay in 2001,” Lover’s Knot” 1996 and” Dear God”
    1996. Today there is hardly any team that is not being addressed.

    Despite all the differences, in many cases, the husband
    is also convinced of thhe presence of his wife’sparasites folie a deux, the madness of two.

  27. March 23rd, 2014 at 00:10 | #27

    And we can have continuously cast slabs, then the most powerful companies iron would totally dominate sales.
    This is a very determinental as we will see later on, steel is a material, which has hindered the progression of skateboarding.
    And you can see, it brings out; this is what we call a galvanized nail.
    Stewart Levine said, ÄòI don Äôt want to take a clean rag.

    Now, as you are aware that steel is iron a very, very well ventilated.

  28. March 23rd, 2014 at 02:14 | #28

    Now you know where to go and how much it costs, and the indifference 0nline tender curves are on the clean energy side.

    We have emissions that have been repossessed.

    He further said that according to the bids from the mail, which
    are typically an advance over the second highest price.

  29. April 16th, 2014 at 01:37 | #29

    Hi there, just wanted to mention, I enjoyed
    this post. It was helpful. Keep on posting!

  30. May 18th, 2014 at 02:01 | #30

    Hey! I understand this is kind of off-topic but I needed to ask.
    Does managing a well-established website like yours take a
    lot of work? I’m completely new to writing a blog but I do write in my diary daily.
    I’d like to start a blog so I can share my own experience
    and views online. Please let me know if you have any ideas or tips for new
    aspiring bloggers. Thankyou!

  31. May 26th, 2014 at 02:14 | #31

    Excellent goods from you, man. I have understand your stff preious
    to and you are jut too magnificent. I really like what you havve acquired
    here, really like what you’re stating andd thhe way in which you say
    it. You make it enjoyable and you still take care oof to keep it sensible.
    I can’t wait tto read far more from you. This is actually a wonferful web site.

  1. February 25th, 2011 at 12:46 | #1