Saturday, 7 June 2014

TreeMap : lowerEntry (K key) : Get mapping associated with the greatest key strictly less than this key

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

import java.util.*;

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

  lowerEntry = myMap.lowerEntry(1); 

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

Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Lower Entry for the key 6 is
4=wx
Lower Entry 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 TreeMapLowerEntryNullPointer{
 public static void main(String args[]){
  TreeMap<Integer, String> myMap;
  Map.Entry<Integer, String> lowerEntry;
  
  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 Entry for the key null is");
  lowerEntry = myMap.lowerEntry(null);   
 }
}

Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Lower Entry 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.lowerEntry(TreeMap.java:700)
        at TreeMapLowerEntryNullPointer.main(TreeMapLowerEntryNullPointer.java:2
1)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment