Saturday, September 27, 2025
HomeLanguagesJavaTreeMap lastEntry() Method in Java with Examples

TreeMap lastEntry() Method in Java with Examples

The java.util.TreeMap.lastEntry() method is used to returns the key-value mapping associated with the greatest key in this map, or null if the map is empty.

Syntax:

tree_map.lastEntry()

Parameters: The method does not take any parameters.

Return Value: The method returns an entry with the greatest key, or null if this map is empty.

Below examples illustrates the working of java.util.TreeMap.lastEntry() method:

Example 1: When the map is not empty.

Java




// Java program to illustrate
// TreeMap lastEntry() method
import java.util.*;
  
class GFG {
    public static void main(String args[])
    {
  
        // Creating an empty TreeMap
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>();
  
        // Mapping string values to int keys
        tree_map.put(98, "Geeks");
        tree_map.put(100, "For");
        tree_map.put(103, "Geeks");
  
        // Printing last entry of the map
        System.out.println("The last entry is : "
                           + tree_map.lastEntry());
    }
}


Output

The last entry is : 103=Geeks

Example 2: When the map is empty.

Java




// Java program to illustrate
// TreeMap lastEntry() method
import java.util.*;
  
class GFG {
    public static void main(String args[])
    {
  
        // Creating an empty TreeMap
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>();
  
        // Printing last entry of the map
        System.out.println("The last entry is : "
                           + tree_map.lastEntry());
    }
}


Output

The last entry is : null
RELATED ARTICLES

Most Popular

Dominic
32323 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6690 POSTS0 COMMENTS
Nicole Veronica
11857 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11913 POSTS0 COMMENTS
Shaida Kate Naidoo
6806 POSTS0 COMMENTS
Ted Musemwa
7073 POSTS0 COMMENTS
Thapelo Manthata
6763 POSTS0 COMMENTS
Umr Jansen
6768 POSTS0 COMMENTS