Write a Java program to get the portion of this map whose keys are less than (or equal to, if inclusive is true) a given key


This Java program demonstrates the usage of the headMap() method of the TreeMap class to get the entries whose keys are less than a specified key. Here is how the program works:

  • A TreeMap object is created and initialized with some key-value pairs.
  • The headMap() method is used to retrieve a view of the entries whose keys are less than a specified key. The method takes a single argument, which is the key that serves as an upper bound for the keys in the returned view.
  • The boolean value true is passed as a second argument to the headMap() method to include the entries that have the specified key as well.
  • The method returns a SortedMap view of the entries, which is then printed to the console using the System.out.println() method.

For example, if we call s1.headMap(103, true) , the program retrieves a view of the entries whose keys are less than or equal to 103, and includes the entry with the key 103.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class GetKey
{  
	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 101 Key(s) : " + s1.headMap(101, true));
		System.out.println("Checking the 103 Key(s) : " + s1.headMap(103, true));
		System.out.println("Checking the 107 Key(s) : " + s1.headMap(107, true));
	}
}

Output

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

Example Programs