Saturday, 7 June 2014

TreeMap : higherEntry (K key) : get the Mapping with least key strictly greater than the given key

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

import java.util.*;

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

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

Output
Elements in myMap are
{2=w, 4=wx, 6=wxy, 8=wxyz}
Higher 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.getHigherEntry(TreeMap.java:463)
        at java.util.TreeMap.higherEntry(TreeMap.java:766)
        at TreeMapHigherEntryNullPointer.main(TreeMapHigherEntryNullPointer.java
:22)





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment