Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

SortedMap — a map ordered by keys

SortedMap orders keys by their natural ordering or a comparator. firstKey() and lastKey() return the endpoint keys in that ordering; both throw an exception for an empty map.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

SortedMap<Integer, String> map = new TreeMap<>();
map.put(10, "A");
map.put(30, "C");
Integer first = map.firstKey();
Integer last = map.lastKey();

SortedMap<K, V> is a map interface ordered by keys, not values or insertion order. It uses natural ordering or a Comparator. Iteration follows that ordering too. TreeMap is an implementation.

SortedMap.firstKey (firstKey()) returns the first key, while SortedMap.lastKey (lastKey()) returns the last. Neither removes entries nor returns values. With a reverse comparator, the first key can be numerically largest. Both methods throw NoSuchElementException when the map is empty.

Keys must be mutually comparable. A comparison result of zero means the same map key; ordering should be consistent with equals to preserve the Map contract.

The example uses TreeMap with natural numeric ordering: although 30 is inserted first, the endpoint keys are 10 and 30. Documentation scope: Java SE 21; the production runtime has not been attested.

Examples

import java.util.SortedMap;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        SortedMap<Integer, String> map = new TreeMap<>();
        map.put(30, "C");
        map.put(10, "A");
        map.put(20, "B");

        System.out.println(map.firstKey());
        System.out.println(map.lastKey());
        map.forEach((key, value) -> System.out.println(key + "=" + value));
    }
}

Result

10
30
10=A
20=B
30=C

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources