What is the TreeMap.lastEntry() method in Java?

Overview

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.

Syntax

The syntax of the TreeMap.lastEntry() method is given below:

Map.entry lastEntry();

Parameters

TreeMap.lastEntry() does not require any parameters.

Return value

The TreeMap.lastEntry() method returns one value:

  • Entry: The key-value pair associated with the greatest key in the map.

Code

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());
}
}

Explanation

  • In line 1, we import the required package.
  • In line 6, we declare a TreeMap that consists of keys of type Integer and values of type String.
  • From lines 8-12, we use the TreeMap.put() method to insert values in the TreeMap.
  • In line 14, we use the TreeMap.lastEntry() method and display the key-value pair associated with the greatest key in the map with a message.
  • From lines 17-26, we create another 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.

Free Resources