A navigable set is a specialized type sorted set.
It provides four methods, lower(), floor(), higher(), and ceiling(), that are used to search for an element based on search criteria.
TreeSet class implements the NavigableSet interface.
The following code uses navigable sets.
It uses integers as the elements of the NavigableSet.
import java.util.NavigableSet; import java.util.TreeSet; public class Main { public static void main(String[] args) { // Create a navigable set and add some integers NavigableSet<Integer> ns = new TreeSet<>(); ns.add(1);/*from ww w . j av a 2 s.c o m*/ ns.add(2); ns.add(3); ns.add(4); ns.add(5); // Get a reverse view of the navigable set NavigableSet reverseNs = ns.descendingSet(); // Print the normal and reverse views System.out.println("Normal View of the Set: " + ns); System.out.println("Reverse view of the set: " + reverseNs); // Get and print a subset of the navigable set System.out.println("\nGetting subset of the set"); NavigableSet threeOrMore = ns.tailSet(3, true); System.out.println("3 or more: " + threeOrMore); // Search the navigable set System.out.println(); System.out.println("Searching through the set"); System.out.println("lower(3): " + ns.lower(3)); System.out.println("floor(3): " + ns.floor(3)); System.out.println("higher(3): " + ns.higher(3)); System.out.println("ceiling(3): " + ns.ceiling(3)); // Poll the navigable set System.out.println(); System.out.println("Polling elements from the set"); // Poll elements one by one and look at the set System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); System.out.println("pollLast(): " + ns.pollLast()); System.out.println("Navigable Set: " + ns); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); // Since the set is empty, polling will return null System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("pollLast(): " + ns.pollLast()); } }