Java TreeMap lastKey() Method
Example
Get the last key of a sorted map:
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<String, String> capitalCities = new TreeMap<String, String>();
capitalCities.put("England", "London");
capitalCities.put("Austria", "Wien");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities.lastKey());
}
}
Definition and Usage
The lastKey() method returns the last key in the map. A TreeMap keeps its keys sorted, so this is the highest key (for text keys, the one that comes last in alphabetical order).
If the map is empty, the method throws a NoSuchElementException.
Tip: Use the firstKey() method to get the first key.
Syntax
public K lastKey()
K refers to the data type of the keys in the map.
Parameter Values
None.
Technical Details
| Returns: | The last (highest) key in the map. |
|---|---|
| Throws: | NoSuchElementException - if the map is empty. |
Related Pages
❮ TreeMap Methods