Java Utility Library

Java TreeMap - tailMap() Method



The java.util.TreeMap.tailMap() method returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey. 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> tailMap(K fromKey,
                                 boolean inclusive)

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


Parameters

fromKey Specify the low endpoint (inclusive) of the keys in the returned map.
inclusive Specify true if the low endpoint is to be included in the returned view.

Return Value

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

Exception

  • Throws ClassCastException, if fromKey is not compatible with this map's comparator (or, if the map has no comparator, if fromKey does not implement Comparable).
  • Throws NullPointerException, if fromKey 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 fromKey lies outside the bounds of the range.

Example:

In the example below, the java.util.TreeMap.tailMap() method returns a view of the portion of the given map containing keys greater 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 tailmap (limiting the key till key is 103)
    NavigableMap<Integer, String> Map2 = new TreeMap<Integer, String>();
    Map2 = Map1.tailMap(103, false); 

    //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: {104=Jo, 105=Sam}

❮ Java.util - TreeMap