Java TreeMap firstEntry() Method
Example
Get the first entry of a sorted map, and the value of that entry:
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.firstEntry());
System.out.println(capitalCities.firstEntry().getValue());
}
}
Definition and Usage
The firstEntry() method returns the entry (a key/value pair) with the first key in the map. A TreeMap keeps its keys sorted, so this is the entry with the lowest key.
Use getKey() and getValue() on the entry to get its key and its value. If the map is empty, the method returns null.
Tip: Use the firstKey() method if you only need the key.
Syntax
public Map.Entry<K,V> firstEntry()
K refers to the data type of the keys in the map, and V refers to the data type of the values.
Parameter Values
None.
Technical Details
| Returns: | The entry with the first (lowest) key, or null if the map is empty. |
|---|
Related Pages
❮ TreeMap Methods