Java Program to get highest key stored in TreeMap


Use the lastKey() method to get the highest key stored in TreeMap.

Let us first set the TreeMap and add some elements to it −

TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"PHP");
m.put(2,"jQuery");
m.put(3,"JavaScript");
m.put(4,"Ruby");
m.put(5,"Java");
m.put(6,"AngularJS");
m.put(7,"ExpressJS");

Now get the highest key −

m.lastKey()

The following is an example to get the highest key in TreeMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"PHP");
      m.put(2,"jQuery");
      m.put(3,"JavaScript");
      m.put(4,"Ruby");
      m.put(5,"Java");
      m.put(6,"AngularJS");
      m.put(7,"ExpressJS");
      System.out.println("TreeMap Elements...
"+m);       System.out.println("Highest key in TreeMap: " + m.lastKey());    } }

Output

TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Highest key in TreeMap: 7

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements