The NavigableSet
interface is part of the Java Collections Framework and is included in the java.util
package. It extends the SortedSet
interface and adds navigation methods for querying the set based on closest matches.
It is most commonly implemented by the TreeSet
class, which stores elements in a sorted, ascending order and allows efficient log(n) time complexity for most operations.
1. NavigableSet
Overview
- A
NavigableSet
is a sorted set that provides methods to navigate the elements relative to a given element. - It does not allow duplicate elements, like all sets.
- All operations rely on either natural ordering (via
Comparable
) or a custom comparator (viaComparator
). - It extends:
java.util.Set<E> -> java.util.SortedSet<E> -> java.util.NavigableSet<E>
- Provides extra navigation methods for floor, ceiling, higher, lower, and subset views.
2. Key Features of NavigableSet
- Sorted Order:
Elements are stored in ascending order according to their natural ordering or a custom comparator. - Navigation Methods:
Allows finding elements closest to a given value without manually iterating over the set. - Subset Views:
Provides methods to retrieve ranges of elements (subSet
,headSet
,tailSet
) that are live views of the set. - Efficient Operations:
Most operations (add, remove, contains, navigation) run in O(log n) time when usingTreeSet
. - Descending Order Views:
Supports a reverse-order view of the set.
3. Implementations
The most commonly used implementation is:
TreeSet
:- Implements
NavigableSet
and stores elements in sorted order using a red-black tree. - Supports all optional operations of the
NavigableSet
interface.
- Implements
Other potential implementations could exist, but TreeSet
is the standard.
4. Commonly Used Methods
Here’s a detailed breakdown of NavigableSet
methods with examples:
4.1 Basic Set Operations
- add(E e): Adds an element to the set if it is not already present.
- remove(Object o): Removes an element if present.
- contains(Object o): Checks if the element exists.
NavigableSet<Integer> set = new TreeSet<>(); set.add(10); set.add(20); set.add(15); System.out.println(set); // [10, 15, 20] set.remove(15); System.out.println(set.contains(15)); // false
4.2 Navigation Methods
- lower(E e): Returns the greatest element less than
e
, ornull
if none exists. - floor(E e): Returns the greatest element less than or equal to
e
. - ceiling(E e): Returns the smallest element greater than or equal to
e
. - higher(E e): Returns the smallest element greater than
e
.
NavigableSet<Integer> set = new TreeSet<>(Arrays.asList(10, 20, 30, 40)); System.out.println(set.lower(25)); // 20 System.out.println(set.floor(20)); // 20 System.out.println(set.ceiling(25)); // 30 System.out.println(set.higher(30)); // 40
4.3 Polling Methods
These methods remove and return elements from the set:
- pollFirst(): Removes and returns the first (lowest) element, or
null
if empty. - pollLast(): Removes and returns the last (highest) element, or
null
if empty.
NavigableSet<Integer> set = new TreeSet<>(Arrays.asList(5, 10, 15)); System.out.println(set.pollFirst()); // 5 System.out.println(set.pollLast()); // 15 System.out.println(set); // [10]
4.4 Subset Views
- subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive): Returns a view of elements in the specified range.
- headSet(E toElement, boolean inclusive): Elements less than
toElement
(inclusive or exclusive). - tailSet(E fromElement, boolean inclusive): Elements greater than or equal to
fromElement
(inclusive or exclusive).
NavigableSet<Integer> set = new TreeSet<>(Arrays.asList(10, 20, 30, 40, 50)); NavigableSet<Integer> sub = set.subSet(15, true, 40, false); System.out.println(sub); // [20, 30] NavigableSet<Integer> head = set.headSet(30, true); System.out.println(head); // [10, 20, 30] NavigableSet<Integer> tail = set.tailSet(30, false); System.out.println(tail); // [40, 50]
Note: Subsets are live views, so changes in the view affect the original set.
4.5 Descending Set
- descendingSet(): Returns a view of the set in reverse order.
- descendingIterator(): Iterator to traverse the set in descending order.
NavigableSet<Integer> set = new TreeSet<>(Arrays.asList(10, 20, 30)); NavigableSet<Integer> descSet = set.descendingSet(); System.out.println(descSet); // [30, 20, 10] Iterator<Integer> it = set.descendingIterator(); while(it.hasNext()) { System.out.print(it.next() + " "); // 30 20 10 }
4.6 Size and Emptiness Checks
- size(): Returns the number of elements.
- isEmpty(): Checks if the set is empty.
NavigableSet<String> set = new TreeSet<>(); System.out.println(set.isEmpty()); // true set.add("Java"); System.out.println(set.size()); // 1
5. Use Cases of NavigableSet
- Range Queries:
Efficiently retrieve subsets of elements within a range usingsubSet
,headSet
, ortailSet
. - Closest Match Searches:
Uselower
,floor
,ceiling
, orhigher
to find nearest elements in sorted order.
Example: Finding the closest available time slot in a scheduling application. - Priority Navigation:
pollFirst
andpollLast
allow removing the smallest or largest element efficiently.
Example: Maintaining a leaderboard or priority queue. - Reverse Iteration:
UsedescendingSet
ordescendingIterator
for reverse order traversal. - Sorted Unique Collections:
NavigableSet
maintains sorted order without duplicates, which is useful for ordered datasets like timestamps, IDs, or sorted names.
6. Performance Notes
- TreeSet Implementation: Uses a Red-Black Tree internally.
- Operations like add, remove, contains, and navigation (
lower
,floor
, etc.) run in O(log n) time.
- Operations like add, remove, contains, and navigation (
- Memory Usage: Slightly higher than
HashSet
due to tree nodes storing left/right pointers and parent links. - Comparator Overhead: Using custom comparators can slightly reduce performance but provides flexibility.
7. Summary
The NavigableSet
interface:
- Extends
SortedSet
with powerful navigation methods. - Provides efficient subset views (
subSet
,headSet
,tailSet
). - Allows finding closest elements relative to a given value (
floor
,ceiling
,lower
,higher
). - Supports descending order views and polling operations (
pollFirst
,pollLast
). - Is best implemented using
TreeSet
, offering O(log n) operations. - Ideal for use cases requiring sorted, unique elements with efficient range queries and nearest-neighbor lookups.