Friday 6 June 2014

TreeMap : headMap (K toKey) : Get sorted map whose keys are strictly less than toKey

public SortedMap<K,V> headMap(K toKey)
Returns a view of the portion of this map whose keys are strictly less than toKey.

import java.util.*;

class TreeMapHeadMap{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  SortedMap<Integer, String> mySortedMap;
  
  myMap = new TreeMap<> ();
  
  /* Add Data to myMap */
  myMap.put(1, "a");
  myMap.put(95, "ab");
  myMap.put(25, "ab");
  myMap.put(15, "ab");
  myMap.put(32, "abc");
  myMap.put(100, "abcd");
  
  mySortedMap = myMap.headMap(30);
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  System.out.println("Elements in mySortedMap are");
  System.out.println(mySortedMap);
 }
}

Output
Elements in myMap are
{1=a, 15=ab, 25=ab, 32=abc, 95=ab, 100=abcd}
Elements in mySortedMap are
{1=a, 15=ab, 25=ab}

1. Throws NullPointerException if toKey is null and this map uses natural ordering, or its comparator does not permit null keys.

import java.util.*;

class TreeMapHeadMapNullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  SortedMap<Integer, String> mySortedMap;
  
  myMap = new TreeMap<> ();
  
  /* Add Data to myMap */
  myMap.put(1, "a");
  myMap.put(95, "ab");
  myMap.put(25, "ab");
  myMap.put(15, "ab");
  myMap.put(32, "abc");
  myMap.put(100, "abcd");
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  
  mySortedMap = myMap.headMap(null);
 }
}

Output
Elements in myMap are
{1=a, 15=ab, 25=ab, 32=abc, 95=ab, 100=abcd}
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1290)
        at java.util.TreeMap$NavigableSubMap.<init>(TreeMap.java:1369)
        at java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:1851)
        at java.util.TreeMap.headMap(TreeMap.java:923)
        at java.util.TreeMap.headMap(TreeMap.java:961)
        at TreeMapHeadMapNullPointer.main(TreeMapHeadMapNullPointer.java:21)





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment