Friday, 6 June 2014

TreeMap : headMap (K toKey, boolean inclusive)

public NavigableMap<K,V> headMap(K toKey, boolean inclusive)
Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey. 

import java.util.*;

class TreeMapHeadMap1{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  NavigableMap<Integer, String> navMap1;
  NavigableMap<Integer, String> navMap2;
  
  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");
  
  navMap1 = myMap.headMap(32, true);
  navMap2 = myMap.headMap(32, false);
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  System.out.println("Elements in navMap1 are");
  System.out.println(navMap1);
  System.out.println("Elements in navMap2 are");
  System.out.println(navMap2);
 }
}

Output
Elements in myMap are
{1=a, 15=ab, 25=ab, 32=abc, 95=ab, 100=abcd}
Elements in navMap1 are
{1=a, 15=ab, 25=ab, 32=abc}
Elements in navMap2 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 TreeMapHeadMap1NullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  NavigableMap<Integer, String> navMap1;
  NavigableMap<Integer, String> navMap2;
  
  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);
  
  navMap1 = myMap.headMap(null, true);  
  
 }
}

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 TreeMapHeadMap1NullPointer.main(TreeMapHeadMap1NullPointer.java:22)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment