Open In App

TreeMap subMap() Method in Java with Examples

In Java, subMap() method of TreeMap class is used to return the part or portion of the map defined by the specified range of keys in the parameter. Any changes made in one or the other map will reflect the change in the other map.

Syntax: 



Tree_Map.subMap(K startKey, K endKey)

Parameters: The method takes two parameters of Key type: 

Return Type: The method returns another map containing the part or portion of the map within the specified range.



Exceptions: The method throws three types of exception: 

Note: If startKey is equal to the endKey then a Null Map is returned.

Example 1:




// Java Program to illustrate the subMap() method
// of TreeMap class
  
// Importing required classes
import java.util.*;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating an empty TreeMap by
        // declaring object of integer, string pairs
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>();
  
        // Mapping string values to int keys
        // using put() method
        tree_map.put(10, "Geeks");
        tree_map.put(15, "4");
        tree_map.put(20, "Geeks");
        tree_map.put(25, "Welcomes");
        tree_map.put(30, "You");
  
        // Printing the elements of TreeMap
        System.out.println("The original map is: "
                           + tree_map);
  
        // Displaying the submap
        // using subMap() method
        System.out.println("The subMap is "
                           + tree_map.subMap(15, 30));
    }
}

Output: 
The original map is: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The subMap is {15=4, 20=Geeks, 25=Welcomes}

 

 Example 2:




// Java Program to Illustrate the subMap() method
  
// Importing required classes
import java.util.*;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty TreeMap by
        // declaring object of string, integer pairs
        TreeMap<String, Integer> tree_map
            = new TreeMap<String, Integer>();
  
        // Mapping int values to string keys
        // using put() method
        tree_map.put("Geeks", 10);
        tree_map.put("4", 15);
        tree_map.put("Geeks", 20);
        tree_map.put("Welcomes", 25);
        tree_map.put("You", 30);
  
        // Printing the elements of TreeMap
        System.out.println("The original map is: "
                           + tree_map);
  
        // Displaying the subMap
        // using subMap() method
        System.out.println(
            "The subMap is "
            + tree_map.subMap("Geeks", "Geeks"));
    }
}

Output: 
The original map is: {4=15, Geeks=20, Welcomes=25, You=30}
The subMap is {}

 


Article Tags :