TreeMap subMap(K fromKey K toKey) method in java

Let’s learn TreeMap subMap(K fromKey K toKey) method in java.

TreeMap subMap(K fromKey K toKey) method in java

subMap(K fromKey, K toKey) method of TreeMap class returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.

Syntax:

public SortedMap<K, V> subMap(K fromKey, K toKey)

Parameters:

fromKey low endpoint (inclusive) of the keys in the returned map.

toKey high endpoint (exclusive) of the keys in the returned map.

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).

Implementations may, but are not required to, throw this exception if fromKey or toKey cannot be compared to keys currently in the map.

NullPointerException – if fromKey or toKey is null and this map uses natural ordering, or its comparator does not permit null keys.

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.

Also read – TreeMap in java

Now let’s see example on TreeMap subMap(K fromKey, K toKey) method in java.

import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapSubMapFromKeyMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      SortedMap<Integer, String> sm = new TreeMap<Integer, String>();
      tm.put(18, "violet");
      tm.put(12, "red");
      tm.put(14, "violet");
      tm.put(16, "green");
      tm.put(20, "blue");
      System.out.println("Gett a portion of TreeMap: ");
      sm = tm.subMap(12, 18);
      System.out.println("Sub map values are: " + sm);
   }
}


Output:

Get a portion of TreeMap:
Sub map values are: {12=red, 14=violet, 16=green}