Friday 6 June 2014

TreeMap : ceilingKey(K key) : get the ceiling key specific to this key

public K ceilingKey(K key)
Returns the least key greater than or equal to the given key, or null if there is no such key.

import java.util.*;

class TreeMapCeilingKey{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Integer ceilingKey;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap2 */
  myMap.put(10, "c");
  myMap.put(1, "a");
  myMap.put(15, "d");
  myMap.put(5, "b");
  myMap.put(99, "e");

  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  
  ceilingKey = myMap.ceilingKey(6);
  System.out.print("Ceiling Key for 6 is ");
  System.out.println(ceilingKey);
  
  ceilingKey = myMap.ceilingKey(100);
  System.out.print("Ceiling Key for 100 is ");
  System.out.println(ceilingKey);
 }
}

Output
Elements in myMap are
{1=a, 5=b, 10=c, 15=d, 99=e}
Ceiling Entry for 6 is 10
Ceiling Entry for 100 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 TreeMapCeilingKeyNullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Integer ceilingKey;
  
  myMap = new TreeMap<> ();
  
  /* Add Elements to myMap2 */
  myMap.put(10, "c");
  myMap.put(1, "a");
  myMap.put(15, "d");
  myMap.put(5, "b");
  myMap.put(99, "e");

  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  
  System.out.println("Ceiling Key for null is ");
  ceilingKey = myMap.ceilingKey(null);
  System.out.println(ceilingKey);
 }
}

Output
Elements in myMap are
{1=a, 5=b, 10=c, 15=d, 99=e}
Ceiling Key for null is
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1290)
        at java.util.TreeMap.getCeilingEntry(TreeMap.java:397)
        at java.util.TreeMap.ceilingKey(TreeMap.java:755)
        at TreeMapCeilingKeyNullPointer.main(TreeMapCeilingKeyNullPointer.java:2
1)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment