What is NavigableSet in Java?

NavigableSet is an interface that inherits the SortedSet interface, which extends the Set interface. All of these are available in the java.util package. The SortedSet interface is implemented by the TreeSet class.

The NavigableSet has all the properties of the SortedSet and also adds a feature with navigation properties with the help of navigation methods. The NavigationSet is useful when we need to navigate throughout a SortedSet in a particular manner with the help of the supporting methods, in order to retain the desired output.

Syntax

NavigableSet<dataType> name = new TreeSet<dataType>();

Code

Let’s have a look at the code and see how NavigableSet is created, as well as one of the operations of NavigableSet.

import java.util.NavigableSet;
import java.util.TreeSet;
class Main
{
public static void main(String args[])
{
NavigableSet<Integer> set = new TreeSet<Integer>();
set.add(1);
set.add(8);
set.add(5);
set.add(3);
set.add(0);
set.add(22);
set.add(10);
System.out.println(" Original NavigableSet: " + set);
NavigableSet<Integer> rset = set.descendingSet();
System.out.println(" Reverse order of the original NavigableSet: " + rset);
}
}

Explanation

  • In lines 1 to 2, we imported the required packages.

  • In line 4 we made a Main class.

  • In line 6, we made a main() function.

  • In line 8, we created a NavigableSet of Integer type which is implemented by the TreeSet class.

  • From lines 10 to 16, we added the elements into the TreeSet by using the TreeSet.add() method.

  • In line 17, we displayed the original NavigableSet with a message.

  • In line 19, we made another NavigableSet to store the elements in the reverse order of the original NavigableSet using a navigation method, i.e., NavigableSet.descendingSet().

  • In line 20, we displayed the reverse order NavigableSet with a message.

So, this is how to create and use a navigation method to display NavigableSet in Java.

Free Resources