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 package
import java.util.*;
// Main class
class Main
{
// main driver function
public static void main(String[] args)
{
// creating an empty TreeMap
TreeMap<Integer, String> treemap = new TreeMap<Integer,String>();
// inserting values in the TreeMap
treemap.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 treemap
System.out.println("TreeMap mappings are: "+ treemap);
// checking for key-value pairs for different keys in the TreeMap
System.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 Main class.

  • In line 8, we make a main() function.

  • In line 11, we declare a TreeMap that 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.

Free Resources