Java Utility Library

Java TreeMap - headMap() Method



The java.util.TreeMap.headMap() method 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 is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.

Syntax

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

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

toKey Specify the high endpoint of the keys in the returned map.
inclusive Specify true if the high endpoint is to be included in the returned view.

Return Value

Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.

Exception

  • 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).
  • Throws NullPointerException, if toKey is null and this map uses natural ordering, or its comparator does not permit null keys.
  • Throws IllegalArgumentException, if this map itself has a restricted range, and toKey lies outside the bounds of the range.

Example:

In the example below, the java.util.TreeMap.headMap() method returns a view of the portion of the given map containing keys less than (or equal to, if inclusive is true) the specified value.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> Map1 = new TreeMap<Integer, String>();

    //populating Map1
    Map1.put(102, "John");
    Map1.put(103, "Marry");
    Map1.put(101, "Kim");
    Map1.put(104, "Jo");
    Map1.put(105, "Sam");

    //printing the Map1
    System.out.println("Map1 contains: " + Map1); 

    //creating the headmap (limiting the key till key is 103)
    NavigableMap<Integer, String> Map2 = new TreeMap<Integer, String>();
    Map2 = Map1.headMap(103, true); 

    //printing the Map2
    System.out.println("Map2 contains: " + Map2);     
  }
}

The output of the above code will be:

Map1 contains: {101=Kim, 102=John, 103=Marry, 104=Jo, 105=Sam}
Map2 contains: {101=Kim, 102=John, 103=Marry}

❮ Java.util - TreeMap