Java TreeMap.ceilingKey(K key) example

In this java tutorial, You will learn how to use ceilingKey() method of TreeMap class.The ceilingKey(K key) method is used to return the least key greater than or equal to the given key, or null if there is no such key.

Returns the least key greater than or equal to the given key, or null if there is no such key.

syntax

public K ceilingKey(K key)

Parameters

key - the key

Returns

the least key greater than or equal to key, or null if there is no such key.

Throws

ClassCastException - if the specified key cannot be compared with the keys currently in the map.

NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

Java TreeMap ceilingKey(K key) example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.ceilingKey(3); It will return ceilingkey "3" for the specific key (3)
  • students.ceilingKey(5); It will return ceilingkey "8" for the specific key "5".
package com.technicalkeeda;

import java.util.TreeMap;

public class App {
    public static void main(String args[]) {

        TreeMap < Integer, String > students = new TreeMap < Integer, String > ();

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");
        students.put(8, "Mahesh");

        System.out.println("TreeMap values :- " + students);

        System.out.println("Ceiling key for 3 :-  " + students.ceilingKey(3));

        System.out.println("Ceiling key for 5 :-  " + students.ceilingKey(5));
    }
}

output

TreeMap values :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi, 8=Mahesh}
Ceiling key for 3 :-  3
Ceiling key for 5 :-  8