Skip to Content

Get Tail Map from Java TreeMap example

  1. /*
  2.   Get Tail Map from Java TreeMap example
  3.   This Java Example shows how to get the portion of TreeMap whose keys
  4.   are grater than or equal to the specified key using tailMap method
  5.   of Java TreeMap class.
  6. */
  7.  
  8. import java.util.SortedMap;
  9. import java.util.TreeMap;
  10.  
  11. public class GetTailMapFromTreeMapExample {
  12.  
  13.   public static void main(String[] args) {
  14.  
  15.     //create TreeMap object
  16.     TreeMap treeMap = new TreeMap();
  17.    
  18.     //add key value pairs to TreeMap
  19.     treeMap.put("1","One");
  20.     treeMap.put("3","Three");
  21.     treeMap.put("2","Two");
  22.     treeMap.put("5","Five");
  23.     treeMap.put("4","Four");
  24.  
  25.     /*
  26.       To get a Tail Map from Java TreeMap use,
  27.       SortedMap tailMap(Object fromKey) method of Java TreeMap class.
  28.      
  29.       This method returns the portion of TreeMap whose keys are grater than
  30.       or equal to fromKey.
  31.  
  32.       Please note that, the SortedMap returned by this method is backed by
  33.       the original TreeMap. So any changes made to SortedMap will be
  34.       reflected back to original TreeMap.
  35.     */
  36.    
  37.     SortedMap sortedMap = treeMap.tailMap("2");
  38.    
  39.     System.out.println("Tail Map Contains : " + sortedMap);
  40.    
  41.     /*
  42.       Please also note that,
  43.       - SortedMap throws IllegalArgumentException for any attempts to insert the
  44.       key less than fromKey.
  45.      
  46.       - subMap throws ClassCastException, if fromKey can not be compared using
  47.       Map's Comparators
  48.     */
  49.    
  50.    
  51.   }
  52. }
  53.  
  54. /*
  55. Output would be
  56. Tail Map Contains : {2=Two, 3=Three, 4=Four, 5=Five}
  57. */