In Java, navigableKeySet() returns the keys of a TreeMap as a NavigableSet in ascending order. It is the same view that keySet() returns, but typed so that set navigation methods such as floor, ceiling, headSet, and pollFirst are available.
The set is live: it reflects every change to the map, and removing elements from it removes mappings. It was added in Java 6 along with NavigableMap.
An instance method of java.util.TreeMap, added in Java 6 (JDK 1.6) with the NavigableMap interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.
Syntax
Hold the result as a NavigableSet to reach the extra methods.
If you just loop over the keys, keySet() is enough. Reach for navigableKeySet() when you want to hand out a set that supports nearest-key questions without exposing the values.
Library declarations
Java
// java.util.TreeMap<K, V>
public NavigableSet<K> navigableKeySet()
// Declared in NavigableMap<K, V> (Java 6)
Keep the intersection. Only c1 and c7 are in both the map and active; c2 and c4 are removed and retainAll reports true.
Extra ids are ignored. "c8" is in the list but not in the map; retainAll never adds anything, it only removes.
Adding needs a value. Trying to add "c8" through the key set throws UnsupportedOperationException; a new cart has to come from carts.put.
Frequently Asked Questions
They return the same live view of the keys. keySet() is declared to return a Set, while navigableKeySet() is declared to return a NavigableSet, exposing floor, ceiling, headSet, and similar methods.
No. It is a live view; it changes when the map changes.
No. add() throws UnsupportedOperationException. Use put on the map.
Yes. Removing a key from the set removes the whole mapping from the TreeMap.
In Java 6, together with NavigableMap and NavigableSet.