Write a Java program to get the least key strictly greater than the given key. Return null if there is no such key


The LeastKey program demonstrates how to use the higherEntry() method of the TreeMap class to retrieve the key-value mapping associated with the least key strictly greater than the specified key. Here's what the program does:

  • It creates a new TreeMap object called s1 and adds five key-value mappings to it.
  • It prints out the contents of the TreeMap using System.out.println().
  • It uses the higherEntry() method to retrieve the key-value mapping associated with the least key strictly greater than 102. It prints out this mapping using System.out.println().
  • It uses the higherEntry() method to retrieve the key-value mapping associated with the least key strictly greater than 107. It prints out this mapping using System.out.println().

Source Code

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

Output

Given TreeMap : {101=John, 102=Charles, 103=Joes, 104=George, 105=Smith}
Checking the 102 Key(s) : 103=Joes
Checking the 107 Key(s) : null

Example Programs