TreeMap потолочный ключ () в Java с примерами

Опубликовано: 4 Февраля, 2022

Функция потолкаKey () класса TreeMap возвращает наименьший ключ, больший или равный заданному ключу, или ноль, если такой ключ отсутствует.

Синтаксис:

 публичный потолок Key (клавиша K)

Параметры: этот метод принимает ключ обязательного параметра, который является ключом для поиска.

Возвращаемое значение: этот метод возвращает наименьший ключ, который больше или равен заданному значению ключа.
Если такой ключ отсутствует, возвращается null.

Исключения: этот метод вызывает следующие исключения:

  • ClassCastException - выбрасывается, если указанный ключ не может быть сравнен с заданными значениями ключа.
  • NullPointerException - выбрасывается, если данный ключ имеет значение NULL, а карта использует естественный порядок или компаратор не допускает значения NULL.

Ниже приведены примеры, иллюстрирующие метод потолочного ключа ():

Program 1: To demonstrate use of ceilingKey() method for a TreeMap with comparator

import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
  
        // creating tree map
        NavigableMap<Integer, String>
            treemap = new TreeMap<Integer,
                                  String>((a, b)
                                              -> ((a > b)
                                                      ? 1
                                                      : ((a == b)
                                                             ? 0
                                                             : -1)));
  
        // populating tree map
        treemap.put(1, " A ");
        treemap.put(2, " B ");
        treemap.put(3, " C ");
        treemap.put(4, " D ");
        treemap.put(6, " E ");
        try {
            System.out.println("Ceiling key entry for 5: "
                               + treemap.ceilingKey(5));
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
Output:
Ceiling key entry for 5: 6

Program 2: To demonstrate use of ceilingKey() method for a TreeMap without any comparator

import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
  
        // creating tree map
        NavigableMap<Integer, String>
            treemap = new TreeMap<Integer, String>();
  
        // populating tree map
        treemap.put(1, " A ");
        treemap.put(2, " B ");
        treemap.put(3, " C ");
        treemap.put(4, " D ");
        treemap.put(6, " E ");
        treemap.put(7, " F ");
  
        // Since 6 is the least value greater than 5,
        // it is returned as the key.
        System.out.println("Ceiling key entry for 5: "
                           + treemap.ceilingKey(5));
    }
}
Output:
Ceiling key entry for 5: 6

Program 3: To demonstrate use of ceilingKey() method when it will return null

import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
  
        // creating tree map
        NavigableMap<Integer, String>
            treemap = new TreeMap<Integer, String>();
  
        // populating tree map
        treemap.put(1, " A ");
        treemap.put(2, " B ");
        treemap.put(3, " C ");
        treemap.put(4, " E ");
        treemap.put(5, " D ");
  
        // Since 10 is not present in the Map
        // and neither any Key is present greater than 10
        // Hence this will return null
        System.out.println("Ceiling key entry for 10: "
                           + treemap.ceilingKey(10));
    }
}
Output:
Ceiling key entry for 10: null

Program 4: To show NullPointerException

import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
  
        // creating tree map
        TreeMap<Integer, String>
            treemap = new TreeMap<Integer, String>();
  
        // populating tree map
        treemap.put(2, " two ");
        treemap.put(1, " one ");
        treemap.put(3, " three ");
        treemap.put(6, " six ");
        treemap.put(5, " five ");
  
        try {
            // returns a NullPointerException
            // as key value can"t be null
            // because of natural ordering
            System.out.println("Ceiling key entry for null value : "
                               + treemap.ceilingKey(null));
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
Output:
Exception: java.lang.NullPointerException

Program 5: To demonstrate ClassCastException

import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
  
        // creating tree map
        NavigableMap<Object, String>
            treemap = new TreeMap<Object, String>();
  
        // populating tree map
        treemap.put(1, " A ");
        treemap.put(2, " B ");
        treemap.put(3, " C ");
        treemap.put(4, " E ");
        treemap.put(5, " D ");
  
        try {
            // returns ClassCastException
            // as we cannot compare a String object with an Integer object
            System.out.println("Ceiling key entry for "asd": "
                               + treemap.ceilingKey(new String("asd")));
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
Output:
Exception: java.lang.ClassCastException: 
           java.lang.Integer cannot be cast to java.lang.String

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .