Syntax error Get last key from NavigableMap in Java

Get last key from NavigableMap in Java



To display the last key from NavigableMap in Java, use the lastKey() method.

Let us first create NavigableMap −

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

Get the last key now −

n.lastKey()

The following is an example to get the last key from NavigableMap.

Example

 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"+n);
      System.out.println("Last Key is "+n.lastKey());
   }
}

Output

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

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements