TreeMap subMap() method in java

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

TreeMap subMap() method in java

subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) method of TreeMap class 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.

Syntax:

public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)


Parameters:

fromKey low endpoint of the keys in the returned map.

fromInclusive true if the low endpointis to be included in the returned view.

toKey high endpoint of the keys in the returned map.

toInclusive true if the high endpoint is to be included in the returned view.

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() method in java.

import java.util.NavigableMap;
import java.util.TreeMap;
public class TreeMapSubMapMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      NavigableMap<Integer, String> nm = 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("Get a portion of TreeMap: ");
      nm = tm.subMap(12, true, 18, true);
      System.out.println("Sub map values are: " + nm);
   }
}


Output:

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