Java TreeMap ceilingKey() Method
Example
Find the closest key that is equal to or after a given key:
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<String, String> capitalCities = new TreeMap<String, String>();
capitalCities.put("England", "London");
capitalCities.put("Austria", "Wien");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities.ceilingKey("France"));
System.out.println(capitalCities.ceilingKey("England"));
}
}
Definition and Usage
The ceilingKey() method returns the least (lowest) key in the map that is greater than or equal to the specified key. For text keys, "greater than" means "comes after in alphabetical order".
The specified key does not have to be in the map. If it is in the map, the method returns that key. If all keys are less than the specified key, the method returns null.
Tip: Use the floorKey() method to find the closest key that is equal to or before a given key.
Syntax
public K ceilingKey(K key)
K refers to the data type of the keys in the map.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key to compare with. It does not have to be in the map. |
Technical Details
| Returns: | The least key that is greater than or equal to key, or null if there is no such key. |
|---|
Related Pages
❮ TreeMap Methods