
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Highest Key Stored in TreeMap in Java
In this article, we will learn how to retrieve the highest key stored in a TreeMap. We will create a simple Java program that demonstrates how to create a TreeMap, add key-value pairs to it, and then use the lastKey() method to find the highest key in the map.
Problem Statement
Write a Java program to get the highest key stored in TreeMap.
Input
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Output
Highest key in TreeMap: 7
Steps
The followingare the steps to get the highest key in TreeMap ?
- First, import the classes.
- Initialize the Demo class.
- Inside the main method creates a TreeMap where keys are integers and values are strings.
- Add elements to the tree
- Print the highest key in the TreeMap.
Java program to get the highest key stored in TreeMap
The following is an example to get the highest key in TreeMap ?
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...\n"+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
Code Explanation
The code demonstrates the use of a TreeMap in Java. First, we will import all the classes by using java.util package and in the main method the TreeMap object m is created, and several key-value pairs are added to it using the put() method, then insert entries into the map, ensuring that the keys are stored in ascending order. We will display all elements and then use, the lastKey() method is used to retrieve and print the highest key in the map, which in this case is 7.