Java TreeMap floorKey() Method
Example
Find the closest key that is equal to or before 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.floorKey("France"));
System.out.println(capitalCities.floorKey("Norway"));
}
}
Definition and Usage
The floorKey() method returns the greatest key in the map that is less than or equal to the specified key. For text keys, "less than" means "comes before 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 greater than the specified key, the method returns null.
Tip: Use the ceilingKey() method to find the closest key that is equal to or after a given key.
Syntax
public K floorKey(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 greatest key that is less than or equal to key, or null if there is no such key. |
|---|
Related Pages
❮ TreeMap Methods