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

1 COMMENT

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS