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