TreeMap lowerKey() in Java with Examples
Last Updated :
17 Sep, 2018
Pre-requisite: TreeMap in Java
The lowerKey() method is used to return the greatest key strictly less than to given key, passed as the parameter. In simpler words, this method is used to find the next greatest element after the element passed as the parameter.
Syntax:
public K TreeMap.lowerKey(K key)
Parameters: This method takes a mandatory parameter key which is this is the key to be matched.
Return Value: This method returns the greatest key strictly less than to key, or null if there is no such key.
Exception: This method throws following exceptions:
- ClassCastException: When the specified key cannot be compared with the key available in Map.
- NullPointerException: When the specified key in map is null and it uses natural
ordering which means, comparator does not permit null keys.
Below are examples to illustrate the use of lowerKey() method:
Example 1:
import java.util.TreeMap;
public class FloorKeyDemo {
public static void main(String args[])
{
TreeMap<Integer, String>
numMap = new TreeMap<Integer, String>();
numMap.put( 6 , "Six" );
numMap.put( 1 , "One" );
numMap.put( 5 , "Five" );
numMap.put( 3 , "Three" );
numMap.put( 8 , "Eight" );
numMap.put( 10 , "Ten" );
System.out.println( "TreeMap: " + numMap.toString());
System.out.print( "Lower Key Entry of Element 9 is: " );
System.out.println(numMap.lowerKey( 9 ));
System.out.print( "Lower Key Entry of Element 3 is: " );
System.out.println(numMap.lowerKey( 3 ));
}
}
|
Output:
TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Lower Key Entry of Element 9 is: 8
Lower Key Entry of Element 3 is: 1
Example 2: To demonstrate NullPointerException
import java.util.TreeMap;
public class FloorKeyDemo {
public static void main(String args[])
{
TreeMap<Integer, String>
numMap = new TreeMap<Integer, String>();
numMap.put( 6 , "Six" );
numMap.put( 1 , "One" );
numMap.put( 5 , "Five" );
numMap.put( 3 , "Three" );
numMap.put( 8 , "Eight" );
numMap.put( 10 , "Ten" );
System.out.println( "TreeMap: " + numMap.toString());
try {
System.out.println(numMap.lowerKey( null ));
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
}
|
Output:
TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Exception: java.lang.NullPointerException
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...