The NavigableSet Interface – Collections: Part II
By Jaime Williams / April 23, 2023 / No Comments / Executing Stream Pipelines, Introduction to Streams, Oracle Certification Exam
The NavigableSet<E> Interface
The NavigableSet<E> interface extends the SortedSet<E> interface with navigation methods to find the closest matches for given search targets. By navigation we mean operations that require searching for elements in the navigable set. In the absence of elements, these operations return null rather than throwing a NoSuchElement-Exception, as is the case for the methods in the SortedSet<E> interface.
The NavigableSet<E> interface replaces the SortedSet<E> interface and is the preferred choice when a sorted set is required. In addition to the methods of the Sorted-Set<E> interface, the NavigableSet<E> interface adds the following new methods:
// First-last elements
E pollFirst()
E pollLast()
The pollFirst() method removes and returns the first element and the poll-Last() method removes and returns the last element currently in this navigable set. The element is determined according to some policy employed by the set—for example, queue policy. Both return null if the sorted set is empty.
// Range-view operations
NavigableSet<E> headSet(E toElement, boolean inclusive)
NavigableSet<E> tailSet(E fromElement, boolean inclusive)
NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
E toElement, boolean toInclusive)
These operations are analogous to the ones in the SortedSet<E> interface (p. 810), returning different views of the underlying navigable set, depending on the bound elements. However, the bound elements can be excluded or included by the operation, depending on the value of the boolean argument inclusive.
// Closest-matches
E ceiling(E e)
E floor(E e)
E higher(E e)
E lower(E e)
The method ceiling() returns the least element in the navigable set greater than or equal to argument e. The method floor() returns the greatest element in the navigable set less than or equal to argument e. The method higher() returns the least element in the navigable set strictly greater than argument e. The method lower() returns the greatest element in the navigable set strictly less than argument e. All methods return null if the required element is not found.
// Reverse order
Iterator<E> descendingIterator()
NavigableSet<E> descendingSet()
The first method returns a reverse-order iterator for the navigable set. The second method returns a reverse-order view of the elements in the navigable set.