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


This program is written in Java and uses a TreeMap to store key-value pairs. The program outputs all keys that are greater than 102. Here is a step-by-step explanation of the program:

  • The program creates a new TreeMap called s1 and adds five key-value pairs to it.
  • The program prints out the TreeMap using System.out.println().
  • The program uses the tailMap() method to get a view of the portion of the TreeMap whose keys are greater than 102. The false argument passed to tailMap() means that the key 102 is not included in the view.
  • The program prints out the result using System.out.println().

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class GreaterKey
{  
	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 102 : " + s1.tailMap(102, false));
	}
}

Output

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

Example Programs