Write a Java program to get the portion of a map whose keys range from a given key to another key


The program demonstrates how to use the subMap method of the TreeMap class to get a subset of keys and their corresponding values from a TreeMap.

  • First, a TreeMap named s1 is created and initialized with key-value pairs.
  • Then, a SortedMap named s2 is created, which will store the subset of key-value pairs that we want to extract from s1.
  • The subMap method is called on s1, with arguments (101, true, 103, true) . This method returns a view of the portion of the TreeMap whose keys range from 101 to 103, inclusive.
  • The returned SortedMap view is assigned to s2.
  • Finally, the program prints out the original TreeMap and the SortedMap subset that was extracted using the subMap method.

Source Code

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

Output

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

Example Programs