Open In App

NavigableMap ceilingKey() method in Java

Improve
Improve
Like Article
Like
Save
Share
Report

The ceilingKey() method of NavigableMap interface in Java is used to return the least key greater than or equal to the given key, or null if there is no such key exists.

Syntax:

K ceilingKey(K key)

Where, K is the type of Key maintained by this map container.

Parameters: It accepts a single parameter Key which is the key to be mapped and is of the type of key accepted by this collection.

Return Value: It returns the least key greater than or equal to the given key, or null if there is no such key exists.

Below programs illustrate the ceilingKey() method in Java:

Program 1: When the key is integer.




// Java code to demonstrate the working of
// ceilingKey()  method
  
import java.io.*;
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Declaring the NavigableMap of Integer and String
        NavigableMap<Integer, String> tmmp = new TreeMap<>();
  
        // assigning the values in the NavigableMap
        // using put()
        tmmp.put(2, "two");
        tmmp.put(7, "seven");
        tmmp.put(3, "three");
  
        // Use of ceilingKey()
        // returns 7( next greater key)
        System.out.println("The next greater key of 6 is : "
                           + tmmp.ceilingKey(6));
  
        // returns "null" as no value present
        // greater than or equal to number
        System.out.println("The next greater key of 3 is : " 
                                       + tmmp.ceilingKey(3));
    }
}


Output:

The next greater key of 6 is : 7
The next greater key of 3 is : 3

Program 2: When the key is string.




// Java code to demonstrate the working of
// ceilingKey()  method
  
import java.io.*;
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Declaring the NavigableMap of Integer and String
        NavigableMap<String, String> tmmp = new TreeMap<>();
  
        // assigning the values in the NavigableMap
        // using put()
        tmmp.put("one", "two");
        tmmp.put("six", "seven");
        tmmp.put("two", "three");
  
        // Use of ceilingKey()
        // returns 7( next greater key)
        System.out.println("The next greater key of five is : "
                           + tmmp.ceilingKey("five"));
  
        // returns "null" as no value present
        // greater than or equal to number
        System.out.println("The next greater key of six is : "
                                         tmmp.ceilingKey("six"));
    }
}


Output:

The next greater key of five is : one
The next greater key of six is : six

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#ceilingKey(K)



Last Updated : 29 Sep, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads