TreeMap tailMap(K fromKey) method in java

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

TreeMap tailMap(K fromKey) method in java

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

Syntax:

public SortedMap<K, V> tailMap(K fromKey)

Parameters:

fromKey low endpoint (inclusive) of the keys in the returned map.

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

import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapTailMapMethodExample
{
   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(14);
      System.out.println("Tail map values are: " + sm);
   }
}

Output:

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


Also read – java overview