Write a Java program to get a key-value mapping associated with the greatest key less than or equal to the given key


This Java program demonstrates the use of the floorEntry() method of the TreeMap class to find the greatest key-value pair less than or equal to the specified key. Here's how it works:

  • We create a TreeMap object called s1 and populate it with some key-value pairs.
  • We print out the original TreeMap using System.out.println("Given TreeMap : " + s1);
  • We use the floorEntry() method to find the greatest key-value pair less than or equal to the specified key.
    • We call s1.floorEntry(101) to find the greatest key-value pair less than or equal to 101.
    • We call s1.floorEntry(106) to find the greatest key-value pair less than or equal to 106.
  • We print out the results using System.out.println().

Source Code

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

Output

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

Example Programs