TreeMap lastEntry() method in java

Let’s learn TreeMap lastEntry() method in java.

TreeMap lastEntry() method in java

lastEntry() method of TreeMap class returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.


public Map.Entry<K, V> lastEntry()


lastEntry() method do not accept any parameters.

Now let’s see example on TreeMap lastEntry() method.

import java.util.TreeMap;
public class TreeMapLastEntryMethodExample
   public static void main(String[] args)
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(96, "mango");
      tm.put(39, "grapes");
      tm.put(56, "pineapple");
      tm.put(93, "apple");
      tm.put(69, "watermelon");
      // get value with greatest key
      System.out.println("Check last entry in given TreeMap: ");
      System.out.println("Value is: "+ tm.lastEntry());


Check last entry in given TreeMap:
Value is: 96=mango

Also read – interface in java