Thursday, December 18, 2025
HomeLanguagesJavaNavigableMap lastEntry() method in Java

NavigableMap lastEntry() method in Java

The lastEntry() method of NavigableMap interface in Java is used to return a key-value mapping associated with the greatest key in this map, or null if the map is empty.

Syntax:

Map.Entry< K, V > lastEntry()

Where, K is the type of key maintained by this map and V is the type of values mapped to the keys.

Parameters: It does not accepts any parameter.

Return Value: It returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

Below programs illustrate the lastEntry() method in Java:

Program 1: When the key is integer.




// Java code to demonstrate the working of
// lastEntry() method
  
import java.io.*;
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Declaring the NavigableMap of Integer and String
        NavigableMap<Integer, String> nmmp = new TreeMap<>();
  
        // assigning the values in the NavigableMap
        // using put()
        nmmp.put(2, "two");
        nmmp.put(7, "seven");
        nmmp.put(3, "three");
  
        System.out.println("The mapping with greatest key is : "
                           + nmmp.lastEntry());
    }
}


Output:

The mapping with greatest key is : 7=seven

Program 2: When the key is string.




// Java code to demonstrate the working of
// lastEntry() method
  
import java.io.*;
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Declaring the NavigableMap of Integer and String
        NavigableMap<String, String> tmmp = new TreeMap<>();
  
        // assigning the values in the NavigableMap
        // using put()
        tmmp.put("one", "two");
        tmmp.put("six", "seven");
        tmmp.put("two", "three");
  
        System.out.println("The mapping associated with greatest key is : "
                           + tmmp.lastEntry());
    }
}


Output:

The mapping associated with greatest key is : two=three

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#lastEntry()

RELATED ARTICLES

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
108 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11957 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12034 POSTS0 COMMENTS
Shaida Kate Naidoo
6957 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6909 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS