TreeMap floorEntry() Method in Java With Examples
The java.util.TreeMap.floorEntry() method is used to return 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.
Syntax:
tree_map.floorEntry(K key)
Parameters: This method takes one parameter key to be matched while mapping.
Return Value: This method returns an entry with the greatest key less than or equal to key, or null if there is no such key.
Exceptions:
- ClassCastException : This exception is thrown if the specified key cannot be compared with the keys currently in the map.
- NullPointerException : This exception is thrown if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
Example 1: When there is a key
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeMap<Integer, String> treemap
= new TreeMap<Integer, String>();
treemap.put( 20 , "Twenty" );
treemap.put( 10 , "Ten" );
treemap.put( 13 , "Thirteen" );
treemap.put( 60 , "Sixty" );
treemap.put( 50 , "Fifty" );
System.out.println( "The greatest key-value less than 18 is : "
+ treemap.floorEntry( 18 ));
}
}
|
Output
The greatest key-value less than 18 is : 13=Thirteen
Example 2: When there is no such key
Java
import java.util.TreeMap;
public class GFG {
public static void main(String args[])
{
TreeMap<Integer, String> treemap
= new TreeMap<Integer, String>();
treemap.put( 10 , "Akash" );
treemap.put( 20 , "Pratik" );
treemap.put( 30 , "Vaibhav" );
treemap.put( 40 , "Sagar" );
treemap.put( 50 , "Abhishek" );
System.out.println( "The greatest key-value less than 5 is : "
+ treemap.floorEntry( 5 ));
}
}
|
Output
The greatest key-value less than 5 is : null
Last Updated :
02 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...