Friday, 6 June 2014

TreeMap : floorKey (K key) : Get the Floor key specific to this key

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

import java.util.*;

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

Output
Elements in myMap are
{1=a, 32=abc, 95=ab, 100=abcd}
Floor key of 50 is
32

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 TreeMapFloorKeyNullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Integer floorKey;
  
  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.println("Floor key of null is");
  
  floorKey = myMap.floorKey(null);
  
  System.out.println(floorKey);
 }
}

Output
Elements in myMap are
{1=a, 32=abc, 95=ab, 100=abcd}
Floor key of null is
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1290)
        at java.util.TreeMap.getFloorEntry(TreeMap.java:429)
        at java.util.TreeMap.floorKey(TreeMap.java:733)
        at TreeMapFloorKeyNullPointer.main(TreeMapFloorKeyNullPointer.java:20)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment