Course contentsShow
← Java
Lesson 975 of 2,87023. Collections Framework OverviewFree lesson

NavigableSet and NavigableMap: Enhanced Navigation

Explore extended interfaces providing ceiling, floor, higher, and lower methods for precise element navigation.

NavigableSet and NavigableMap: Enhanced Navigation

What you'll learn: How NavigableSet and NavigableMap extend sorted collections with precise navigation methods for finding nearby elements.

Beyond Simple Sorting

You already know that SortedSet and SortedMap maintain elements in sorted order. But what if you need to find the closest element to a target value? Or the next larger element? This is where NavigableSet and NavigableMap come in—they extend the sorted interfaces with powerful navigation methods that let you "walk around" your collection with precision.

The Navigation Methods

Think of a sorted collection as a staircase. SortedSet tells you where the staircase starts and ends. NavigableSet lets you ask questions like: "Which step is just below my current position?" or "What's the next step above me?"

Key NavigableSet Methods

  • ceiling(E e) – Returns the smallest element ≥ e (the "ceiling" above you)
  • floor(E e) – Returns the largest element ≤ e (the "floor" below you)
  • higher(E e) – Returns the smallest element strictly > e (step up)
  • lower(E e) – Returns the largest element strictly < e (step down)

NavigableMap Methods

NavigableMap<K,V> provides similar navigation but works with keys:

  • ceilingKey(K key), floorKey(K key), higherKey(K key), lowerKey(K key) – Navigate by keys
  • Also includes ceilingEntry, floorEntry, higherEntry, lowerEntry – Return full key-value mappings

When to Use Them

These interfaces are perfect for range queries, finding nearest matches, or implementing algorithms that need "closest value" lookups—like finding the nearest timestamp in a log, or the price tier just below a threshold.

Key Takeaway: NavigableSet and NavigableMap add ceiling, floor, higher, and lower methods to sorted collections, enabling precise navigation to nearby elements without manual iteration.