Write a Java program to get the first (lowest) key and the last (highest) key currently in a map


The program first creates a TreeMap object called s1 that maps integer keys to string values. It then adds five key-value pairs to the TreeMap using the put() method.

To find the greatest and least keys in the TreeMap, the program uses the firstKey() and lastKey() methods of the TreeMap object. firstKey() returns the first (i.e., lowest) key in the TreeMap, while lastKey() returns the last (i.e., highest) key in the TreeMap.

Finally, the program prints the original TreeMap and the results of the firstKey() and lastKey() methods using println() statements.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class GreatestLeast_Key
{  
	public static void main(String args[])
	{
		TreeMap<Integer,String> s1 = new TreeMap<Integer,String>();
		s1.put(101, "Joes");
		s1.put(102, "Charles");		
		s1.put(103, "John");
		s1.put(104, "George");
		s1.put(105, "Smith");
 
		System.out.println("Given TreeMap : " + s1);
		System.out.println("Greatest Key : " + s1.firstKey());
		System.out.println("Least Key : " + s1.lastKey());
	}
}

Output

Given TreeMap : {101=Joes, 102=Charles, 103=John, 104=George, 105=Smith}
Greatest Key : 101
Least Key : 105

Example Programs