TreeMap headMap() method in java

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

TreeMap headMap() method in java

headMap() method of TreeMap class returns a view of the portion of this map whose keys are strictly less than toKey.

Syntax:

public SortedMap<K, V> headMap(K toKey)

Parameters:

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

Throws:

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.

Also read – TreeMap in java

Now let’s see example on TreeMap headMap() method.

import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapHeadMapMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      // map string values to integer keys
      tm.put(65, "mango");
      tm.put(63, "apple");
      tm.put(35, "grapes");
      tm.put(60, "pineapple");
      tm.put(26, "banana");
      System.out.println("Given TreeMap is: " + tm);
      // create SortedMap for map head
      SortedMap<Integer, String> sm = new TreeMap<Integer, String>();
      sm = tm.headMap(60);
      // Getting map head
      System.out.println("headmap is: " + sm);
   }
}


Output:

Given TreeMap is: {26=banana, 35=grapes, 60=pineapple, 63=apple, 65=mango}
headmap is: {26=banana, 35=grapes}


Let’s see another example where we map integer values to String keys.

import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapHeadMapMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
      // map string values to integer keys
      tm.put("mango", 65);
      tm.put("apple", 63);
      tm.put("grapes", 35);
      tm.put("pineapple", 60);
      tm.put("banana", 26);
      System.out.println("Given TreeMap is: " + tm);
      // create SortedMap for map head
      SortedMap<String, Integer> sm = new TreeMap<String, Integer>();
      sm = tm.headMap("pineapple");
      // Getting map head
      System.out.println("headmap is: " + sm);
   }
}


Output:

Given TreeMap is: {apple=63, banana=26, grapes=35, mango=65, pineapple=60}
headmap is: {apple=63, banana=26, grapes=35, mango=65}