The TreeMap.lastEntry() method is used to obtain the key-value mapping that is associated with the greatest key in the map.
The TreeMap.lastEntry() method is present in the TreeMap class inside the java.util package.
The syntax of the TreeMap.lastEntry() method is given below:
Map.entry lastEntry();
TreeMap.lastEntry() does not require any parameters.
The TreeMap.lastEntry() method returns one value:
Entry: The key-value pair associated with the greatest key in the map.Let’s have a look at the code.
import java.util.*;class Main{public static void main(String[] args){TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();t1.put(1, "Let's");t1.put(5, "see");t1.put(2, "TreeMap class");t1.put(27, "methods");t1.put(9, "in java.");System.out.println("The key-value mapping associated with " +"the lowest key in the map is: " + t1.lastEntry());TreeMap<String, Integer> t2 = new TreeMap<String, Integer>();t2.put("ab", 5);t2.put("baa", 1);t2.put("cbc", 2);t2.put("d", 27);t2.put("e", 9);System.out.println("The key-value mapping associated with " +"the lowest key in the map is: " + t2.lastEntry());}}
TreeMap that consists of keys of type Integer and values of type String.TreeMap.put() method to insert values in the TreeMap.TreeMap.lastEntry() method and display the key-value pair associated with the greatest key in the map with a message.TreeMap object that contains keys of type String and the values of type Integer. We can see in the output that the greatest key in the case of strings is considered based on alphabetic order.So, this is the way to use the TreeMap.lastEntry() method in Java.