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>)

France
Paris
Japan
Tokyo

Contains Key

Check a specific key exist in a map using containsKey method. Example countryCapcityMap.containsKey('Japan');

Japan

Result

The map containsKey() method returns a boolean value. In the following example, it returns true.

true

Check if the map contains a key using the containsKey() method.

Following is an example of using the containsKey() method in a map.

Loading...

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 returns false .

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.

Try It Yourself

Loading...