What is the TreeMap.ceilingEntry() method in Java?
Introduction
The TreeMap.ceilingEntry() method is present in the TreeMap interface, inside the java.util package.
The TreeMap.ceilingEntry() method is used to return a key-value pair of the least key greater than or equal to the key passed as an argument.
Syntax
public Map.Entry<K,V> ceilingEntry(K key)
Parameter
The TreeMap.ceilingEntry() method accepts one parameter, which is the key that needs to be matched.
Return value
The TreeMap.ceilingEntry() method returns either of these two values:
-
Key-value: It returns this value when the key-value pair of the least key is greater than or equal to the key that was passed as an argument. -
Null: It returns this value if no such key exists.
Code
// importing required packageimport java.util.*;// Main classclass Main{// main driver functionpublic static void main(String[] args){// creating an empty TreeMapTreeMap<Integer, String> treemap = new TreeMap<Integer,String>();// inserting values in the TreeMaptreemap.put(2,"Welcome");treemap.put(12,"to");treemap.put(31,"Educative.io");treemap.put(18,"Learn");treemap.put(25,"Coding");treemap.put(36,"Java");// displaying the mappings of the treemapSystem.out.println("TreeMap mappings are: "+ treemap);// checking for key-value pairs for different keys in the TreeMapSystem.out.println("The key-value pair obtained for the key 18 is: " + treemap.ceilingEntry(18));System.out.println("The key-value pair obtained for the key 27 is: " + treemap.ceilingEntry(27));System.out.println("The key-value pair obtained for the key 40 is: " + treemap.ceilingEntry(40));}}
Explanation
-
In line 2, we import the required package.
-
In line 5, we make a
Mainclass. -
In line 8, we make a
main()function. -
In line 11, we declare a
TreeMapthat consists of keys of type integer and values of type string. -
From lines 14 to 19, we insert values in the map by using the
TreeMap.put()method. -
In line 22, we display the mappings present in the
TreeMap. -
From lines 25 to 27, we use the
TreeMap.ceilingEntry()method to get a key-value pair of the least key that is greater than or equal to the key passed as an argument and display it.
This is how we can use the TreeMap.ceilingEntry() method in Java.
Please refer to the What is the
TreeMap.ceilingKey()method in Java? for more information on this topic.