Write a Java program to get a key-value mapping associated with the greatest key and the least key in a map


This program demonstrates how to find the greatest and least key-value pairs in a TreeMap in Java. Explanation of the program:

  • First, a TreeMap object named s1 is created with Integer as key and String as value.
  • Then, five key-value pairs are added to the TreeMap using the put() method.
  • The TreeMap is printed using System.out.println() method.
  • The firstEntry() method of the TreeMap is used to get the greatest key-value pair and it is printed using System.out.println() method.
  • Similarly, the lastEntry() method is used to get the least key-value pair and it is also printed using System.out.println() method.

firstEntry() method returns the first (lowest) key-value pair in the TreeMap and lastEntry() method returns the last (highest) key-value pair in the TreeMap.

Source Code

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

Output

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

Example Programs