In this tutorial, we will learn about the Java NavigableSet interface and its methods with the help of an example.
The NavigableSet interface of the Java Collections framework provides the features to navigate among the set elements.
NavigableSet represents a navigable set in Java Collection Framework. The NavigableSet interface inherits from the SortedSet interface. It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet. For example, NavigableSet interface can navigate the set in reverse order compared to the order defined in SortedSet.
// A Java program to demonstrate working of SortedSet
import java.util.NavigableSet;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
// Creating NavigableSet using the TreeSet
NavigableSet<Integer> numbers = new TreeSet<>();
// Insert elements to the set
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("NavigableSet: " + numbers);
// Access the first element
int firstElement = numbers.first();
System.out.println("First Number: " + firstElement);
// Access the last element
int lastElement = numbers.last();
System.out.println("Last Element: " + lastElement);
// Remove the first element
int number1 = numbers.pollFirst();
System.out.println("Removed First Element: " + number1);
// Remove the last element
int number2 = numbers.pollLast();
System.out.println("Removed Last Element: " + number2);
}
}
output:
NavigableSet: [1, 2, 3]
First Element: 1
Last Element: 3
Removed First Element: 1
Removed Last Element: 3
Method | Description |
---|---|
Lower(E e) | Returns the greatest element in this set which is less than the given element or NULL if there is no such element. |
Floor(E e) | Returns the greatest element in this set which is less than or equal to given element or NULL if there is no such element. |
Ceiling(E e) | Returns the least element in this set which is greater than or equal to given element or NULL if there is no such element. |
Higher(E e) | Returns the least element in this set which is greater than the given element or NULL if there is no such element. |
pollFirst() | Retrieve and remove the first least element. Or return null if there is no such element. |
pollLast() | Retrieve and remove the last highest element. Or return null if there is no such element. |