Thursday, October 16, 2025
HomeLanguagesJavaSortedMap lastKey() method in Java

SortedMap lastKey() method in Java

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:




// A Java program to demonstrate
// working of SortedSet
import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
        // Create a TreeSet and inserting elements
        SortedMap<Integer, String> mp = new TreeMap<>();
  
        // Adding Element to SortedSet
        mp.put(1, "One");
        mp.put(2, "Two");
        mp.put(3, "Three");
        mp.put(4, "Four");
        mp.put(5, "Five");
  
        // Returning the last key from the map
        System.out.print("Last Key in the map is : "
                         + mp.lastKey());
    }
}


Output:

Last Key in the map is : 5

Program 2:




// A Java program to demonstrate
// working of SortedSet
import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
        // Create a TreeSet and inserting elements
        SortedMap<String, String> mp = new TreeMap<>();
  
        // Adding Element to SortedSet
        mp.put("One", "Geeks");
        mp.put("Two", "For");
        mp.put("Three", "Geeks");
        mp.put("Four", "Code");
        mp.put("Five", "It");
  
        // Returning the last key from the map
        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()

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11953 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS