Java TreeMap navigableKeySet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 6+

Definition

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.

Java
TreeMap<Integer, Integer> stock = new TreeMap<>();
NavigableSet<Integer> sizes = stock.navigableKeySet();
Integer smaller = sizes.floor(42);     // greatest size <= 42
Integer larger = sizes.ceiling(42);    // least size >= 42
CallWhat it does
map.navigableKeySet()Ascending keys as a live NavigableSet.
set.headSet(k)Keys below k, also live.
set.tailSet(k, true)Keys from k up, also live.

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)

Parameters

ParameterDescription
(none)navigableKeySet takes no parameters.

Return Value

Return ValueDescription
NavigableSet<K>A live, ascending view of the map's keys.

Compare with Similar Methods

Key views compared:

MethodHow it differs
keySet()Same view, declared as Set<K>.
descendingKeySet()Keys in reverse order.
floorKey(k)The map's own nearest-key lookup.
headMap(k)Range view that keeps the values.

Java Examples

Example 1 — Nearest Shoe Sizes in Stock

The key set answers "closest smaller" and "closest larger" without touching the stock counts.

Java
import java.util.NavigableSet;
import java.util.TreeMap;

public class TreeMapNavigableKeySetSizes {
    public static void main(String[] args) {
        TreeMap<Integer, Integer> stock = new TreeMap<>();
        stock.put(40, 6);
        stock.put(38, 2);
        stock.put(44, 1);
        stock.put(41, 4);

        NavigableSet<Integer> sizes = stock.navigableKeySet();
        System.out.println("sizes: " + sizes);
        System.out.println("size 42 -> smaller: " + sizes.floor(42) + ", larger: " + sizes.ceiling(42));
        System.out.println("above 44: " + sizes.higher(44));
    }
}

How It Works

  1. A sorted set of sizes. The view prints the four sizes in ascending order, independent of the order they were stocked.
  2. Set navigation. Size 42 is missing, so floor(42) suggests 41 and ceiling(42) suggests 44.
  3. Nothing larger than the largest. higher(44) has no answer and returns null.

Example 2 — Split Members Into Two Live Halves

headSet and tailSet of the key set are live too, so a new member lands in the right half automatically.

Java
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeMap;

public class TreeMapNavigableKeySetHalves {
    public static void main(String[] args) {
        TreeMap<String, Integer> members = new TreeMap<>();
        members.put("Tess", 4);
        members.put("Ana", 1);
        members.put("Mo", 3);
        members.put("Ben", 2);

        NavigableSet<String> names = members.navigableKeySet();
        SortedSet<String> early = names.headSet("M");
        NavigableSet<String> late = names.tailSet("M", true);
        System.out.println("A-L: " + early + ", M-Z: " + late);

        members.put("Lars", 5);
        System.out.println("A-L after put: " + early);
    }
}

How It Works

  1. Two typed results. headSet("M") returns a SortedSet, while the boolean form tailSet("M", true) returns a NavigableSet.
  2. A split at "M". Names sorting before "M" go to the first half and "Mo" and "Tess" to the second, with no name in both.
  3. Views of views stay live. "Lars" was put into the map, and it appears in early without rebuilding anything.

Example 3 — Keep Only Active Carts With retainAll()

retainAll on the key set removes every cart whose id is not in the active list.

Java
import java.util.Arrays;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeMap;

public class TreeMapNavigableKeySetRetain {
    public static void main(String[] args) {
        TreeMap<String, Integer> carts = new TreeMap<>();
        carts.put("c1", 3);
        carts.put("c2", 1);
        carts.put("c4", 2);
        carts.put("c7", 5);

        List<String> active = Arrays.asList("c1", "c7", "c8");
        NavigableSet<String> ids = carts.navigableKeySet();
        System.out.println("changed: " + ids.retainAll(active));
        System.out.println("carts: " + carts);
        try {
            ids.add("c8");
        } catch (UnsupportedOperationException e) {
            System.out.println("ids.add: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Keep the intersection. Only c1 and c7 are in both the map and active; c2 and c4 are removed and retainAll reports true.
  2. Extra ids are ignored. "c8" is in the list but not in the map; retainAll never adds anything, it only removes.
  3. 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.

Next: pollFirstEntry()

Remove and return the pair with the smallest key.

pollFirstEntry() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful