Java Utility Library

Java TreeMap - subMap() Method



The java.util.TreeMap.subMap() method returns a view of the portion of this map whose keys range from fromKey to toKey. If fromKey and toKey are equal, the returned map is empty unless fromInclusive and toInclusive are both true. 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 NavigableMap<K,V> subMap(K fromKey,
                                boolean fromInclusive,
                                K toKey,
                                boolean toInclusive)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

fromKey Specify the low endpoint of the keys in the returned map.
fromInclusive Specify true if the low endpoint is to be included in the returned view.
toKey Specify the high endpoint of the keys in the returned map.
toInclusive Specify true if the high endpoint is to be included in the returned view.

Return Value

Returns a view of the portion of this map whose keys range from fromKey to toKey.

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
    NavigableMap<Integer, String> Map2 = new TreeMap<Integer, String>();
    Map2 = Map1.subMap(102, true, 104, true); 

    //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, 104=Jo}

❮ Java.util - TreeMap