Saturday 7 June 2014

TreeMap : lowerKey (K key) : Get greatest key strictly less than given key

public K lowerKey(K key)
Returns the greatest key strictly less than the given key, or null if there is no such key.

import java.util.*;

class TreeMapLowerKey{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Integer lowerKey;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap */
  myMap.put(2, "w");
  myMap.put(4, "wx");
  myMap.put(6, "wxy");
  myMap.put(8, "wxyz");
  
  lowerKey = myMap.lowerKey(6);
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  
  System.out.println("Lower key for the key 6 is");
  System.out.println(lowerKey); 

  lowerKey = myMap.lowerKey(1); 

  System.out.println("Lower key for the key 1 is");
  System.out.println(lowerKey);  
 }
}

Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Lower key for the key 6 is
4
Lower key for the key 1 is
null

1. 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 TreeMapLowerKeyNullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Integer lowerKey;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap */
  myMap.put(2, "w");
  myMap.put(4, "wx");
  myMap.put(6, "wxy");
  myMap.put(8, "wxyz");
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  
  System.out.println("Lower key for the key null is");
  lowerKey = myMap.lowerKey(null);
 }
}

Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Lower key for the key null is
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1290)
        at java.util.TreeMap.getLowerEntry(TreeMap.java:494)
        at java.util.TreeMap.lowerKey(TreeMap.java:711)
        at TreeMapLowerKeyNullPointer.main(TreeMapLowerKeyNullPointer.java:20)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment