CKTIS / Java
Extreme keys in SortedMap: firstKey() and lastKey()
`firstKey()` and `lastKey()` return the keys at the ends of the map’s sort order. Both throw `NoSuchElementException` if the map is empty.
Version: Java SE 21
Syntax
In java.util.SortedMap<K,V>:
K firstKey();
K lastKey();SortedMap.firstKey/lastKey refers to two methods on java.util.SortedMap<K,V>: firstKey() returns the first key and lastKey() returns the last. Both take no arguments, return a key of type K rather than a value or a key–value entry, and leave the mappings in place.
The map’s key order determines which key comes first: natural ordering if comparator() returns null, or the order defined by the map’s comparator otherwise. Insertion order does not matter. For keys 10, 70, and 120, natural ordering puts 10 first and 120 last. Comparator.reverseOrder() flips those results: 120 is first and 10 is last.
On an empty map, either call throws NoSuchElementException rather than returning null. If the map cannot change between the check and the lookup, you can check isEmpty() first. In Java SE 21, SortedMap also inherits firstEntry() and lastEntry() from SequencedMap: they return a Map.Entry<K,V>, or null if the map is empty.
Examples
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
SortedMap<Integer, String> natural = new TreeMap<>();
natural.put(70, "middle");
natural.put(120, "high");
natural.put(10, "low");
SortedMap<Integer, String> reverse = new TreeMap<>(Comparator.reverseOrder());
reverse.putAll(natural);
System.out.println("natural: " + natural.firstKey() + "/" + natural.lastKey());
System.out.println("reverse: " + reverse.firstKey() + "/" + reverse.lastKey());
SortedMap<Integer, String> empty = new TreeMap<>();
expectEmptyFailure("firstKey", empty::firstKey);
expectEmptyFailure("lastKey", empty::lastKey);
}
private static void expectEmptyFailure(String method, Runnable call) {
try {
call.run();
} catch (NoSuchElementException expected) {
System.out.println(method + ": NoSuchElementException");
return;
}
throw new AssertionError(method + " did not throw NoSuchElementException");
}
}Result
natural: 10/120 reverse: 120/10 firstKey: NoSuchElementException lastKey: NoSuchElementException
The expected lines `natural: 10/120` and `reverse: 120/10` show the effect of the comparator. The last two lines correspond to the two exceptions caught separately on the empty map.
Related lessons
- Java · Lesson 20 · Advanced · Version: 2