lastKey(): This method is available in java.util.TreeMap class of Java.
Syntax:
K java.util.TreeMap.lastKey()
This method returns the last (highest) key currently on this map.
Parameters: NA
Returns: the last (highest) key currently on this map.
Throws:
NoSuchElementException - if this map is empty
Approach 1: When no exception
Java
import java.util.TreeMap;public class TreeMaplastKey {public static void main(String[] args) {TreeMap<Integer, String> treeMap =new TreeMap<Integer, String>();treeMap.put(2, "Hello");treeMap.put(11, "Java");treeMap.put(23, "Program");treeMap.put(6, "C++");treeMap.put(25, "Program");System.out.println(treeMap.lastKey());}}
Output:
25
Approach 2: NoSuchElementException
Java
import java.util.TreeMap;public class TreeMaplastKey {public static void main(String[] args) {TreeMap<Integer, String> treeMap =new TreeMap<Integer, String>();System.out.println(treeMap.lastKey());}}
Output:
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.TreeMap.key(TreeMap.java:1596) at java.base/java.util.TreeMap.lastKey(TreeMap.java:298)
No comments:
Post a Comment