TreeMap tailMap(K fromKey boolean inclusive) method in java

Let’s learn TreeMap tailMap(K fromKey, boolean inclusive) method in java.

TreeMap tailMap(K fromKey, boolean inclusive) method in java

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

Syntax:

public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)

Parameters:

fromKey low endpoint of the keys in the returned map

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

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).

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

NullPointerException – if fromKey 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 fromKey lies outside the bounds of the range.

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

import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapTailMapBooleanMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      SortedMap<Integer, String> sm = new TreeMap<Integer, String>();
      tm.put(18, "violet");
      tm.put(12, "red");
      tm.put(14, "violet");
      tm.put(16, "green");
      tm.put(20, "blue");
      System.out.println("Get tail map of TreeMap: ");
      sm = tm.tailMap(12, true);
      System.out.println("Tail map values are: " + sm);
   }
}

Output:

Get tail map of TreeMap:
Tail map values are: {12=red, 14=violet, 16=green, 18=violet, 20=blue}


Also read – classes and objects in java