What is SortedMap.lastKey() method in Java?
In this shot, we will discuss how to use the SortedMap.lastKey() method in Java. The SortedMap.lastKey() method is present in the SortedMap interface inside the java.util package.
The SortedMap.lastKey() method is used to obtain the greatest key-element present in the SortedMap.
Parameter
The SortedMap.lastKey() method doesn’t take any parameters.
Return
The SortedMap.lastKey() method returns:
- Key: The greatest key present in the
SortedMap.
Code
Let’s look at the code snippet below.
import java.util.*;class Main{public static void main(String[] args){SortedMap<Integer, String> s = new TreeMap<Integer,String>();s.put(2,"Welcome");s.put(12,"to");s.put(31,"the");s.put(18,"world");s.put(25,"of");s.put(30,"java");System.out.println("SortedMap mappings are: "+ s);System.out.println("The last key in the SortedMap is: " + s.lastKey());}}
Explanation
- In line 1, we import the required package.
- In line 2, we make a
Mainclass. - In line 4, we make a
mainfunction. - In line 6, we declare a
SortedMapconsisting of integer type keys and string type values. - From lines 8 to 13, we insert values in the Hashtable by using the
TreeMap.put()method. - In line 15, we display the mappings of the present in the
SortedMap. - In line 17, we use the
SortedMap.lastKey()method to obtain the greatest key ofSortedMapand display it.
In this way, we can use the SortedMap.lastKey() method in Java.