TreeMap headMap(K toKey boolean inclusive) method in java

Let’s learn TreeMap headMap(K toKey, boolean inclusive) method in java.

TreeMap headMap(K toKey, boolean inclusive) method in java

headMap(K toKey, boolean inclusive) method of TreeMap class returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside its range.


public NavigableMap<K, V> headMap(K toKey, boolean inclusive)


toKey high endpoint of the keys in the returned map.

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


ClassCastException – if toKey is not compatible with this map’s comparator (or, if the map has no comparator, if toKey does not implement Comparable).

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

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

IllegalArgumentException – if this map itself has are stricted range, and toKey lies outside the bounds of the range.

Now let’s see example on TreeMap headMap(K toKey, boolean inclusive) method.

import java.util.NavigableMap;
import java.util.TreeMap;
public class TreeMapHeadMapBooleanInclusiveMethod
   public static void main(String[] args)
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      NavigableMap<Integer, String> nm = new TreeMap<Integer, String>();
      tm.put(96, "violet");
      tm.put(93, "green");
      tm.put(20, "yellow");
      tm.put(36, "red");
      tm.put(53, "blue");
      // get head map inclusive 93
      nm = tm.headMap(93, true);
      System.out.println("Check values of TreeMap");
      System.out.println("Value is: " + nm);


Check values of TreeMap
Value is: {20=yellow, 36=red, 53=blue, 93=green}

Also read – constructor in java