Friday 6 June 2014

TreeMap : floorEntry (K key) : Get the Floor Entry of this key

public Map.Entry<K,V> floorEntry(K key)
Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.

import java.util.*;

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

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

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 TreeMapFloorEntryNullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Map.Entry<Integer,String> floorEntry;
  
  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 Entry of null is");  
  floorEntry = myMap.floorEntry(null);
 }
}


Output
Elements in myMap are
{1=a, 32=abc, 95=ab, 100=abcd}
Floor Entry 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.floorEntry(TreeMap.java:722)
        at TreeMapFloorEntryNullPointer.main(TreeMapFloorEntryNullPointer.java:1
9)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment