In this shot, we will learn how to use the TreeMap.ceilingKey()
method in Java.
The TreeMap.ceilingKey()
method is present in the TreeMap
interface inside the java.util
package.
The TreeMap.ceilingKey()
method is used to return the least key greater than or equal to the key passed as an argument.
The syntax of the TreeMap.ceilingKey()
is shown below:
K ceilingKey(K key)
The TreeMap.ceilingKey()
method accepts one parameter, which is the key which needs to be matched.
The TreeMap.ceilingKey()
method returns either of the two values:
Let’s have a look at the code.
import java.util.*;class Main{public static void main(String[] args){TreeMap<Integer, String> s = new TreeMap<Integer,String>();s.put(2,"Welcome");s.put(12,"to");s.put(31,"Educative.io");s.put(18,"Learn");s.put(25,"Coding");s.put(36,"Java");System.out.println("TreeMap mappings are: "+ s);System.out.println("The key obtained after using " +"ceilingEntry(18) method is: " + s.ceilingKey(20));}}
In line 1, we imported the required package.
In line 2, we made a Main
class.
In line 4, we made a main()
function.
In line 6, we declared a TreeMap
consisting of keys of type Integer
and values of type String
.
From lines 8 to 13, we inserted values in the map by using the TreeMap.put()
method.
In line 15, we displayed the mappings present in the TreeMap
.
In line 17, we used the TreeMap.ceilingKey()
method to get the least key greater than or equal to the key passed as an argument, and we displayed it.
So, this is how to use the TreeMap.ceilingKey()
method in Java.