Home > Java certifications > Java – Navigable Set

Java – Navigable Set


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


public static void main(String[] args) 
    NavigableSet <Integer> navigableSet  = new TreeSet<Integer>();
    Iterator< Integer> iterator = navigableSet.iterator();
    Iterator< Integer> reverseIterator = navigableSet.descendingIterator();
    System.out.println("Forward ahoy !");
    while (iterator.hasNext())
    System.out.println("Reverse yoha !");
    while (reverseIterator.hasNext())


The output of this program would be:
Forward ahoy !
Reverse yoha !

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


The output would be as follows:


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.tailSet(-10, false));
System.out.println(navigableSet.headSet(40, true));

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:



[-10, 10, 20, 40, 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. July 22nd, 2015 at 22:03 | #1

    The NFTS has teamed with the BFI to provide this program, within the BFI Film

  2. July 24th, 2015 at 06:08 | #2

    This article is truly a good one it assists new web people, who are wishing for blogging.

  3. July 25th, 2015 at 06:18 | #3

    ¿Ya lo tienes claro?

  4. July 25th, 2015 at 08:15 | #4

    You should take part in a contest for one of the best websites on the net.
    I am going to recommend this website!

  5. July 26th, 2015 at 15:37 | #5

    Venture capitalist Peter Thiel, however, has taken it a step up–by creating several corporations with Tolkien-inspired names and
    using them to hold shares of Facebook stock. These familiar sources can offer interest-free loans or be a
    minor investor in the business set up. (f) Each capital source should call for your earnest
    contemplation before you go on to the next deal.

  6. July 26th, 2015 at 20:06 | #6

    Thankfulness to my father who shared with me about this
    website, this webpage is in fact awesome.

  7. July 27th, 2015 at 02:08 | #7

    What’s up, everything is going fine here and
    ofcourse every one is sharing data, that’s actually excellent, keep up writing.

  8. July 27th, 2015 at 07:34 | #8

    It’s awesome to pay a quick visit this web site and reading the views of
    all friends concerning this piece of writing, while I am
    also eager of getting know-how.

  9. July 28th, 2015 at 00:43 | #9

    Los productores han confesado que en su día vieron la reacción on-line para la
    Boda Roja, y que lo hicieron como una salvedad justa” a la regla., pero
    esto no es todo, sino asimismo vamos a poder proseguirla a las 22:25 de mañana (trece de abril) en Por otro lado, está la posibilidad
    de poner punto y final a la serie con una película.

  10. July 28th, 2015 at 13:57 | #10

    ʜi, yeah thiѕ pioece of writing is in fact fastidious and I have learned lot of things from iit regarding blogging.

  11. July 28th, 2015 at 15:30 | #11

    Hi friends, fastidious article and good arguments
    commented here, I am actually enjoying by these.

  12. August 1st, 2015 at 22:39 | #12

    Virtual Households Cheats is the website that provides you the best cheats, codes, ideas and
    secrets and techniques on the web.

  13. August 3rd, 2015 at 09:50 | #13

    Which for Huskies, would be at least two years old.
    One of the best ways to fight these issues is to invest in custom vans for college tennis teams.
    Or you could buy Van Roof Racks online and possibly save a bit of money this way.
    Green – Go Tek (GGT Electric) has been a long known name in association with electric vehicle
    technology, and as a result, these inspired businesses have turned to GGT to
    get the cars for their businesses. This passion is still very close
    to his heart see He has recently started training his
    new mate, a female toy poodle. Such flexible systems have developed for the last 20 years post
    considering the valuable feedback and suggestions to
    fit your diverse needs.

  14. August 4th, 2015 at 17:20 | #14

    Very good

  15. August 10th, 2015 at 19:29 | #15

    Make money on autopilot is available for all
    of us. This shows you how user friendly these templates are.
    Well, you may have to consider a lot of things before you
    even plan to launch your website.

  16. August 11th, 2015 at 00:16 | #16

    Oh my goodness! Impressive article dude! Thank you, However I am going through troubles with your RSS.
    I don’t understand why I can’t join it. Is there anybody else getting the
    same RSS problems? Anybody who knows the solution can you kindly
    respond? Thanks!!

  17. August 15th, 2015 at 00:05 | #17

    This is my first time pay a visit at here and i am rewlly happy to read all aat alone place.

  18. August 16th, 2015 at 00:30 | #18

    Generally I don’t learn article on blogs, however I wish to say that this write-up very compelled
    me to take a look at and do so! Your writing taste has been surprised me.
    Thanks, quite great post.

  19. September 1st, 2015 at 01:55 | #19

    Nominal voltage (Un) is the voiltage whuich electrical installations or elements of electrical installations,
    similar to home equipment, hundreds etc.

  20. September 3rd, 2015 at 07:21 | #20

    There are at the moment solely 69 Licensed Grasp HVAC Educators around
    the country, and 19 of them train at Lincoln schools.

  21. September 4th, 2015 at 04:13 | #21

    Esta dieta tiene cuatro pasos a lo largo de los cuales progresivamente vamos
    agregando más hidratos de carbono hasta llegar al peso deseado.

  22. September 5th, 2015 at 05:34 | #22


  23. September 20th, 2015 at 05:57 | #23

    Hi to all, the contents existing at this site are truly amazing for
    people experience, well, keep up the nice work fellows.

  24. September 25th, 2015 at 00:56 | #24

    Since the admin of thiis web site iss working, noo hesitation very shortly it will bbe famous, due
    to its uality contents.

  25. September 25th, 2015 at 03:55 | #25

    Este tipo de avena se puede mezclar con leche y prácticamente se disuelve, con lo
    que se facilita mucho su ingesta.

  26. September 28th, 2015 at 08:12 | #26

    Para la belleza y la salud, la avena cuanta con grandes propiedades, y mejor si se
    emplea la avena en inglés para adelgazar.

  27. October 2nd, 2015 at 12:58 | #27

    Мне действительно нравится читая статья ,
    что сделает Мужчины и женщины думаю.

    Кроме того, благодарим Вас за позволяющие комментарий!

  28. October 5th, 2015 at 18:28 | #28

    Why viewers still use to read news papers when in this technological
    globe everything is existing on net?

  29. October 25th, 2015 at 23:35 | #29

    La adquisición de la licuadora de su sitio web se asegurará de garantías no van a ser canceladas.

    de América) por pieza y dieciocho y sesenta y cuatro (dieciocho dólares estadounidenses y sesenta
    y cuatro centavos de los Como es lógico, la mayor parte de las personas no
    están prestas a poner exactamente el mismo empeño para recobrar su
    salud que el que pusieron para destruirla.

  30. October 26th, 2015 at 15:59 | #30

    Oi, adorei extraordinariamente do seu blog! achei o teor muito bem escrito.
    escrevi um website no mesmo assunto e gostaria de
    ver se você tem alguma sugestão para quem está começando a escrever soobre este tema.

Comment pages
1 2 16
  1. February 25th, 2011 at 12:46 | #1