NavigableMap lastEntry() method in Java

Java 8Object Oriented ProgrammingProgramming

The NavigableMap lastEntry() method returns a key-value mapping associated with the greatest key in this map.

Let us first create a NavigableMap and add some elements to it −

NavigableMap<Integer,String> n = new TreeMap<Integer,String>();
n.put(5, "Tom");
n.put(9, "John");
n.put(14, "Jamie");
n.put(1, "Tim");
n.put(4, "Jackie");
n.put(15, "Kurt");
n.put(19, "Tiger");
n.put(24, "Jacob");

Now, get the last entry −


The following is another example to get last entry from NavigableMap −


 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      NavigableMap<String, Integer> n = new TreeMap<String, Integer>();
      n.put("A", 498);
      n.put("B", 389);
      n.put("C", 868);
      n.put("D", 988);
      n.put("E", 686);
      n.put("F", 888);
      n.put("G", 999);
      n.put("H", 444);
      n.put("I", 555);
      n.put("J", 666);
      System.out.println("NavigableMap elements...
"+n); System.out.println("Last Entry is "+n.lastEntry()); } }


NavigableMap elements...
{A=498, B=389, C=868, D=988, E=686, F=888, G=999, H=444, I=555, J=666}
Last Entry is J=666
Updated on 30-Jul-2019 22:30:24