Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ceilingkey
java
treemap
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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));
}
}
Use TreeMap.ceilingKey() method in Java

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
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring