Checking a key exist in a map
To check if a key exists in a map, use the containsKey()
method. The containsKey() method takes one parameter, the key to check for in the map.
If the map contains the given key, it returns true; otherwise, false.
Map contains key
Original Map
Initial key-value pairs in a map named countryCapcityMap ( map<String, String>)
Contains Key
Check a specific key exist in a map using containsKey method. Example countryCapcityMap.containsKey('Japan');
Result
The map containsKey() method returns a boolean value. In the following example, it returns true.
Check if the map contains a key using the containsKey()
method.
Following is an example of using the containsKey() method in a map.
In the above example:
- The
contains()
method is used to check if the map contains a key. - The contains() methods returns
true
if the map contains the key, otherwise it returnsfalse
.
Note
Alternatively, to check if the map contains a key, you can use the get() method, which returns null
if the key is not present in the map.