What is the TreeMap.floorEntry() method in Java?
In this shot, we will learn how to use the TreeMap.floorEntry() method in Java. It is present in the TreeMap class inside the java.util package.
The TreeMap.floorEntry() method is used to obtain the key-value pair associated with the greatest key less than or equal to the given key in the parameter present in the map currently.
If no such key is present in the TreeMap, it returns null.
Syntax
The syntax of the TreeMap.floorEntry() method is given below:
Map.entry floorEntry();
Parameter
The TreeMap.floorEntry() accepts only one parameter:
Key: The key for which we need to determine the key-value pair.
Return value
The TreeMap.floorEntry() method returns one value:
Entry: It returns the key-value pair associated with the greatest key less than or equal to the given key in the parameter present on the map currently.
Code
Let’s have a look at the code.
import java.util.*;class Main{public static void main(String[] args){TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();t1.put(1, "Let's");t1.put(5, "see");t1.put(2, "TreeMap class");t1.put(27, "methods");t1.put(9, "in java.");System.out.println("The key-value mapping associated with " +"the greatest key in the map is: " + t1.floorEntry(4));TreeMap<String, Integer> t2 = new TreeMap<String, Integer>();t2.put("apple", 98);t2.put("banana", 5);t2.put("carrot", 2);t2.put("dog", 27);t2.put("elephant", 9);System.out.println("The key-value mapping associated with " +"the greatest key in the map is: " + t2.floorEntry("cat"));}}
Explanation
- In line 1, we imported the required package.
- In line 2, we made a
Mainclass. - In line 4, we made a
main()function. - In line 6, we declared a
TreeMapconsisting of keys of typeIntegerand values of typeString. - From lines 8 to 12, we inserted values in the
TreeMapby using theTreeMap.put()method. - In line 14, we used the
TreeMap.floorEntry()method and displayed the key-value pair associated with the greatest key less than or equal to the given key with a message. - From lines 17 to 26, we defined another
TreeMapobject, such that the keys are of typeStringand the values are of typeInteger. Now, we can see in the output that the greatest key-value pair that is less than or equal to the valuecatis displayed. It means that for string based keys, the function returns the key-value pair based on alphabetical order.
So, this is how to use the TreeMap.floorEntry() method in Java.