Write a Java program to get the greatest key less than or equal to the given key


This Java program demonstrates the use of the TreeMap.floorKey() method to find the greatest key less than or equal to a given key.

  • First, a TreeMap object named s1 is created with integer keys and string values.
  • Five key-value pairs are added to the TreeMap using the put() method.
  • The floorKey() method is used to find the greatest key less than or equal to the given key. In the first println() statement, s1.floorKey(101) is used to find the greatest key less than or equal to 101, which is 101 itself. In the second println() statement, s1.floorKey(106) is used to find the greatest key less than or equal to 106, which is 105.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class GreatestKey
{  
	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("Checking the 101 Key : " + s1.floorKey(101));
		System.out.println("Checking the 106 Key : " + s1.floorKey(106));
	}
}

Output

Given TreeMap : {101=Joes, 102=Charles, 103=John, 104=George, 105=Smith}
Checking the 101 Key : 101
Checking the 106 Key : 105

Example Programs