Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

TreeMap lastEntry() Method in Java with Examples

  • Last Updated : 02 Sep, 2020

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!