VOOZH about

URL: https://www.geeksforgeeks.org/java/treemap-submap-method-in-java-with-examples/

⇱ TreeMap subMap() Method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TreeMap subMap() Method in Java with Examples

Last Updated : 11 Jul, 2025

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: 

  • The starting point or lower end of the map including which the points are to be considered. (startKey)
  • The endpoint or the higher end of the map excluding which the points are to be considered.(endKey)

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: 

  • ClassCastException: This exception is thrown if the parameters mentioned in the method cannot be compared with the keys of this map.
  • NullPointerException: This exception is thrown if either of the parameters is of null type and the map does not accept any null values.
  • IllegalArgumentException: This exception is thrown if the mentioned parameters are out of range or the lower end is greater than the higher end.

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

Example 1:


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:


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

 
Comment
Article Tags: