Friday 6 June 2014

TreeMap : get (Object key) : Get the Value mapped to specific key

public V get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

import java.util.*;

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

  System.out.print("Value Associated with key 95 is ");
  System.out.println(myMap.get(95));
  System.out.print("Value Associated with key 99 is ");
  System.out.println(myMap.get(99)); 
 }
}

Output
Elements in myMap are
{1=a, 32=abc, 95=ab, 100=abcd}
Value Associated with key 95 is ab
Value Associated with key 99 is null

1. Throws ClassCastException if the specified key cannot be compared with the keys currently in the map

2. Throws NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys

import java.util.*;

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

  System.out.print("Value Associated with key null is ");
  System.out.println(myMap.get(null));
 }
}

Output
Elements in myMap are
{1=a, 32=abc, 95=ab, 100=abcd}
Value Associated with key null is Exception in thread "main" java.lang.NullPoint
erException
        at java.util.TreeMap.getEntry(TreeMap.java:347)
        at java.util.TreeMap.get(TreeMap.java:278)
        at TreeMapGetNullPointer.main(TreeMapGetNullPointer.java:20)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment