Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Live range views in NavigableMap

Use `subMap`, `headMap`, and `tailMap` to select a key range, explicitly include or exclude its endpoints, and work with the original map rather than a copy.

Version: Java SE 21

Syntax

import java.util.NavigableMap;
import java.util.SortedMap;

// Overloads declared by NavigableMap<K,V>:
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive);
NavigableMap<K,V> headMap(K toKey, boolean inclusive);
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);

// Overloads with fixed boundary rules:
SortedMap<K,V> subMap(K fromKey, K toKey); // [fromKey, toKey)
SortedMap<K,V> headMap(K toKey);           // keys < toKey
SortedMap<K,V> tailMap(K fromKey);         // keys >= fromKey

The NavigableMap.subMap/headMap/tailMap methods in java.util.NavigableMap return views restricted to a range of keys. Bounds follow the map's key order: its comparator, or the keys' natural order if the map has no comparator. The example's TreeMap<Integer, String> uses ascending numeric order.

subMap(fromKey, fromInclusive, toKey, toInclusive) sets both bounds, headMap(toKey, inclusive) sets only the upper bound, and tailMap(fromKey, inclusive) sets only the lower bound. true includes the corresponding endpoint; false excludes it. In the example, subMap(50, true, 100, true) selects [50,100], headMap(60, false) selects <60, and tailMap(90, true) selects >=90.

The overloads with boolean arguments return NavigableMap<K,V>. The shorter overloads have the declared return type SortedMap<K,V> on the interface: subMap(fromKey, toKey) selects [fromKey, toKey), headMap(toKey) selects keys < toKey, and tailMap(fromKey) selects keys >= fromKey.

A view is backed by the original map, not copied from it. If the map supports a mutation, changes made through the view affect the original, and changes to in-range keys in the original appear in the view. Inserting an out-of-range key through a view throws IllegalArgumentException, as does reversing the subMap bounds or requesting a disallowed bound from an already restricted view. If the two endpoints compare as equal, the range can include that key only if both endpoints are inclusive; the entry appears only if it exists.

Examples

import java.util.NavigableMap;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        NavigableMap<Integer, String> scores = new TreeMap<>();
        for (int key : new int[] {49, 50, 60, 90, 100, 101}) {
            scores.put(key, "initial");
        }

        NavigableMap<Integer, String> range = scores.subMap(50, true, 100, true);
        NavigableMap<Integer, String> below60 = scores.headMap(60, false);
        NavigableMap<Integer, String> atLeast90 = scores.tailMap(90, true);

        System.out.println("[50,100]: " + range.keySet());
        System.out.println("<60: " + below60.keySet());
        System.out.println(">=90: " + atLeast90.keySet());

        range.put(90, "updated");
        System.out.println("source[90]: " + scores.get(90));
        scores.put(55, "added");
        System.out.println("head[55]: " + below60.get(55));

        try {
            below60.put(60, "rejected");
        } catch (IllegalArgumentException e) {
            System.out.println("head.put(60): IllegalArgumentException");
        }
    }
}

Result

[50,100]: [50, 60, 90, 100]
<60: [49, 50]
>=90: [90, 100, 101]
source[90]: updated
head[55]: added
head.put(60): IllegalArgumentException

Updating key `90` through `range` changes the original map. Adding key `55` to the original makes it visible in `below60`. `below60.put(60, ...)` throws even though key `60` already exists in the original.

Related lessons

  • Java · Lesson 20 · Advanced · Version: 2

Sources