SortedMap lastKey() method in Java
Last Updated :
26 Nov, 2018
The lastKey() method of SortedMap interface in Java is used to return the last or the greatest key currently in this map.
Syntax:
K lastKey()
Where, K is the type of key maintained by this Set.
Parameters: This function does not accepts any parameter.
Return Value: It returns the last or the greatest key currently in this map
Exception: It throws NoSuchElementException, if this map is empty.
Below programs illustrate the above method:
Program 1:
import java.util.*;
public class Main {
public static void main(String[] args)
{
SortedMap<Integer, String> mp = new TreeMap<>();
mp.put( 1 , "One" );
mp.put( 2 , "Two" );
mp.put( 3 , "Three" );
mp.put( 4 , "Four" );
mp.put( 5 , "Five" );
System.out.print( "Last Key in the map is : "
+ mp.lastKey());
}
}
|
Output:
Last Key in the map is : 5
Program 2:
import java.util.*;
public class Main {
public static void main(String[] args)
{
SortedMap<String, String> mp = new TreeMap<>();
mp.put( "One" , "Geeks" );
mp.put( "Two" , "For" );
mp.put( "Three" , "Geeks" );
mp.put( "Four" , "Code" );
mp.put( "Five" , "It" );
System.out.print( "Last Key in the map is : "
+ mp.lastKey());
}
}
|
Output:
Last Key in the map is : Two
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/SortedMap.html#lastKey()
Share your thoughts in the comments
Please Login to comment...