Java TreeMap - subMap() Method
The java.util.TreeMap.subMap() method returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. (If fromKey and toKey are equal, the returned map is empty.) The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.
Syntax
public SortedMap<K,V> subMap(K fromKey, K toKey)
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
fromKey |
Specify the low endpoint (inclusive) of the keys in the returned map. |
toKey |
Specify the high endpoint (exclusive) of the keys in the returned map. |
Return Value
Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
Exception
- Throws ClassCastException, if fromKey and toKey cannot be compared to one another using this map's comparator (or, if the map has no comparator, using natural ordering).
- Throws NullPointerException, if fromKey or toKey is null and this map uses natural ordering, or its comparator does not permit null keys.
- Throws IllegalArgumentException, if fromKey is greater than toKey; or if this map itself has a restricted range, and fromKey or toKey lies outside the bounds of the range.
Example:
In the example below, the java.util.TreeMap.subMap() method returns a view of the portion of the given map containing keys in the specified range of values.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treemap TreeMap<Integer, String> Map1 = new TreeMap<Integer, String>(); //populating Map1 Map1.put(102, "John"); Map1.put(103, "Marry"); Map1.put(101, "Kim"); Map1.put(104, "Jo"); Map1.put(105, "Sam"); //printing the Map1 System.out.println("Map1 contains: " + Map1); //creating the submap containing keys in the given range SortedMap<Integer, String> Map2 = new TreeMap<Integer, String>(); Map2 = Map1.subMap(102, 104); //printing the Map2 System.out.println("Map2 contains: " + Map2); } }
The output of the above code will be:
Map1 contains: {101=Kim, 102=John, 103=Marry, 104=Jo, 105=Sam} Map2 contains: {102=John, 103=Marry}
❮ Java.util - TreeMap