Java TreeMap firstKey() Method
Example
Get the first 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.firstKey());
}
}
Definition and Usage
The firstKey() method returns the first key in the map. A TreeMap keeps its keys sorted, so this is the lowest key (for text keys, the one that comes first in alphabetical order).
If the map is empty, the method throws a NoSuchElementException.
Tip: Use the lastKey() method to get the last key.
Syntax
public K firstKey()
K refers to the data type of the keys in the map.
Parameter Values
None.
Technical Details
| Returns: | The first (lowest) key in the map. |
|---|---|
| Throws: | NoSuchElementException - if the map is empty. |
Related Pages
❮ TreeMap Methods