This post will discuss how to check whether a given key exists in a Map in Java. The solution should check if the map contains a mapping for a key k such that Objects.equals(key, k) holds for a given key key.

1. Using containsKey() method

The containsKey() method returns true if this map contains a mapping for the specified key. You can use it as follows:

Download  Run Code

 
Note that if a class does not override the equals() and hashCode() methods, and if an object of such class is inserted in a Map as a key, the containsKey() method will return false. To fix this, overload the equals and hashCode methods. Also, note that the containsKey() method throws NullPointerException if the specified key is null and the map implementation does not permit null keys.

2. Using Map.keySet() method

In Java 8 and above, you can get the stream of the keys in the map using the Map.keySet() method, and check if any elements of the stream match with the specified key. This can be done using the anyMatch() method:

Download  Run Code

 
Apache Commons Collections’ CollectionUtils.containsAny() method returns true if any item in the collection matches with any of the specified items. You can use it as follows to find a value in the map:

Download Code

3. Using get() method

If your map doesn’t contain any null value, you can do like:

Download  Run Code

 
The above code will fail if the map contains any null value. This can be handled as follows:

Download  Run Code

That’s all about checking whether a given key exists in a Map in Java.