Let’s learn TreeMap lastKey() method in java.
TreeMap lastKey() method in java
lastKey() method of TreeMap class returns the last (highest) key currently in this map.
Syntax:
public K lastKey()
Parameters:
lastKey() method do not take any parameters.
Throws:
NoSuchElementException – if this map is empty.
Now let’s see example on TreeMap lastKey() method.
import java.util.TreeMap; public class TreeMapLastKeyMethodExample { public static void main(String[] args) { TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); tm.put(99, "yellow"); tm.put(86, "violet"); tm.put(93, "red"); tm.put(36, "green"); tm.put(29, "blue"); System.out.println("Given TreeMap is: " + tm); // display lastKey of TreeMap System.out.println("last key is: " + tm.lastKey()); } }
Output:
Given TreeMap is: {29=blue, 36=green, 86=violet, 93=red, 99=yellow}
last key is: 99
Let’s map integer values to string keys.
import java.util.TreeMap; public class TreeMapLastKeyMethodExample { public static void main(String[] args) { TreeMap<String, Integer> tm = new TreeMap<String, Integer>(); tm.put("yellow", 99); tm.put("violet", 86); tm.put("red", 93); tm.put("green", 36); tm.put("blue", 29); System.out.println("Given TreeMap is: " + tm); // display lastKey of TreeMap System.out.println("last key is: " + tm.lastKey()); } }
Output:
Given TreeMap is: {blue=29, green=36, red=93, violet=86, yellow=99}
last key is: yellow
Also read – nested classes in java