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
// Java program to illustrate // TreeMap floorEntry() method import java.util.*; public class GFG { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Mapping string values to int keys 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
// Java program to illustrate // TreeMap floorEntry() method import java.util.TreeMap; public class GFG { public static void main(String args[]) { // Creating an empty TreeMap TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Mapping string values to int keys treemap.put( 10 , "Akash" ); treemap.put( 20 , "Pratik" ); treemap.put( 30 , "Vaibhav" ); treemap.put( 40 , "Sagar" ); treemap.put( 50 , "Abhishek" ); // Printing floor entry System.out.println( "The greatest key-value less than 5 is : " + treemap.floorEntry( 5 )); } } |
Output
The greatest key-value less than 5 is : null
Please Login to comment...