Java TreeMap headMap() Method Example

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

Signature

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

This method returns the view portion of this map whose keys are strictly less than toKey. Throws ClassCastException  if toKey is not compatible with this map’s comparator and NullPointerException if toKey is null and this map uses natural ordering, or its comparator does not permit null keys and IllegalArgumentException if this map itself has a restricted range, and toKey lies outside the bounds of the range

Example

The following example shows the usage of java.util.TreeMap.headMap(toKey) method.

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class HeadMapMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to populate elements to the TreeMap
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(1,"Element1");
        treeMap1.put(6,"Element6");
        treeMap1.put(5,"Element5");
        treeMap1.put(4,"Element4");
        
        //Print the elements of treeMap1
        System.out.println("**Elements of treeMap1**");
        for (Map.Entry<Integer,String> me : treeMap1.entrySet()) 
        {
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        
        //Get the headMap of key 4
        SortedMap<Integer,String> sortedMap = new TreeMap<Integer,String>();
        sortedMap = treeMap1.headMap(4);
        System.out.println("**HeadMap to key 4**");
        for(Map.Entry<Integer,String> me : sortedMap.entrySet())
        {
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
    }
}

Output

**Elements of treeMap1**
1: Element1
2: Element2
3: Element3
4: Element4
5: Element5
6: Element6
**HeadMap to key 4**
1: Element1
2: Element2
3: Element3

Leave a Reply

Your email address will not be published. Required fields are marked *