Write a Java program to get the portion of a map whose keys range from a given key (inclusive), to another key (exclusive)


This Java program demonstrates the usage of the subMap method of the TreeMap class to get a sub-range of keys and their corresponding values from a given TreeMap.

The program starts by creating a TreeMap object named s1 and adding 6 key-value pairs to it using the put method. Then, a SortedMap object named s2 is declared and initialized to an empty TreeMap.

Next, the subMap method of the s1 object is called with two arguments - 102 (inclusive) and 105 (exclusive) - to get a sub-range of keys and their corresponding values. The resulting SortedMap object is assigned to s2.

Finally, the program prints the original TreeMap object s1 and the sub-range of keys and values in the s2 object.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class KeyRange
{  
	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");
		s1.put(106, "Abi");
 
		SortedMap<Integer,String> s2 = new TreeMap<Integer,String>();
		System.out.println("Given TreeMap : " + s1);
		s2 = s1.subMap(102, 105);
		System.out.println("Sub TreeMap Key Values: " + s2);
	}
}

Output

Given TreeMap : {101=John, 102=Charles, 103=Joes, 104=George, 105=Smith, 106=Abi}
Sub TreeMap Key Values: {102=Charles, 103=Joes, 104=George}

Example Programs