Java TreeMap lastEntry() Method
Example
Get the last 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.lastEntry());
System.out.println(capitalCities.lastEntry().getValue());
}
}
Definition and Usage
The lastEntry() method returns the entry (a key/value pair) with the last key in the map. A TreeMap keeps its keys sorted, so this is the entry with the highest 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 lastKey() method if you only need the key.
Syntax
public Map.Entry<K,V> lastEntry()
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 last (highest) key, or null if the map is empty. |
|---|
Related Pages
❮ TreeMap Methods