Write a Java program to get a portion of a map whose keys are greater than or equal to a given key


The given Java program uses a TreeMap to store key-value pairs and demonstrates how to obtain a portion of the TreeMap based on a key. Here is a brief explanation of the code:

  • First, a TreeMap is created and initialized with key-value pairs.
  • The TreeMap is then printed to the console.
  • The tailMap method is used to get a view of the portion of the TreeMap whose keys are greater than or equal to a specified key.
  • The result is printed to the console.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class Greater_EqualKey
{  
	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("Keys are Greater than or Equal to 103 : " + s1.tailMap(103));
	}
}

Output

Given TreeMap : {101=John, 102=Charles, 103=Joes, 104=George, 105=Smith}
Keys are Greater than or Equal to 103 : {103=Joes, 104=George, 105=Smith}

Example Programs