Trusted answers to developer questions

What is the TreeMap.ceilingKey() method in Java?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

In this shot, we will learn how to use the TreeMap.ceilingKey() method in Java.

Introduction

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.

Syntax

The syntax of the TreeMap.ceilingKey() is shown below:

K ceilingKey(K key)

Parameter

The TreeMap.ceilingKey() method accepts one parameter, which is the key which needs to be matched.

Return

The TreeMap.ceilingKey() method returns either of the two values:

  • Key-value: The least key greater than or equal to the key passed as an argument.
  • Null: If no such key exists.

Code

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));
}
}

Explanation:

  • 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.

RELATED TAGS

ceilingkey
java
treemap
Did you find this helpful?