Course contentsShow
← Java
Lesson 1139 of 2,87026. Map ImplementationsFree lesson

firstKey, lastKey, and Boundary Access

Accessing the minimum and maximum keys efficiently using TreeMap's boundary methods.

firstKey, lastKey, and Boundary Access

You'll learn how to efficiently retrieve the minimum and maximum keys from a TreeMap using its boundary access methods.

The Core Idea

Because TreeMap maintains keys in sorted order (thanks to its red-Black tree structure), it can instantly tell you which key is smallest and which is largest. You don't need to iterate through all entries—the tree structure already knows where these boundary elements live.

Think of it like a sorted filing cabinet: the first and last folders are immediately visible without opening any drawers in between.

Key Boundary Methods

firstKey() returns the smallest key in the map according to the natural ordering or comparator you specified.

lastKey() returns the largest key in the map.

Both methods throw NoSuchElementException if the map is empty, so check before calling them on potentially empty maps.

TreeMap<Integer, String> scores = new TreeMap<>();
scores.put(85, "Alice");
scores.put(92, "Bob");
scores.put(78, "Charlie");

Integer lowest = scores.firstKey();   // 78
Integer highest = scores.lastKey();   // 92

Why This Matters

These operations are O(log n) in TreeMap—extremely fast even for large maps. The tree's balanced structure means the minimum key is always at the leftmost node, and the maximum is at the rightmost node. No scanning required!

This efficiency makes TreeMap ideal when you frequently need to access extreme values, like finding the earliest timestamp, the lowest price, or the highest priority item.

Key Takeaway: TreeMap's firstKey() and lastKey() methods provide efficient O(log n) access to boundary elements, leveraging the sorted tree structure to instantly locate minimum and maximum keys without iteration.