ConcurrentHashMap containsKey() Method in Java
The containsKey() method in Java’s ConcurrentHashMap class is used to determine whether the map contains a given key. It has the following signature:
boolean containsKey(Object key)
key is the key to be searched for in the map.
The containsKey() method works in a concurrent environment, which means that it can be called from multiple threads without causing any data race or synchronization issues.
When a containsKey() operation is performed, the method first acquires the lock on the segment of the map corresponding to the given key and then checks if the key is present in the map. If the key is found, the method returns true. Otherwise, it returns false.
Here is an example of using the containsKey() method:
Map contains key Bob: true Map contains key Dave: false
In this example, we first create a ConcurrentHashMap and add three key-value pairs to it using the put() method.
Next, we perform a containsKey() operation to check if the key “Bob” is present in the map. The method returns true, and we print out the result.
Finally, we perform a containsKey() operation to check if the key “Dave” is present in the map. The method returns false, and we print out the result.
The java.util.concurrent.ConcurrentHashMap.containsKey() method is an in-built function in Java that accepts a parameter and checks whether it is key in this map.
Parameters: The method accepts a single parameter key_element of an object type which is to be checked for whether it is a key or not.
Return Value: The method returns true if the specified key_element is a key of this map and false otherwise.
Exception: The function throws NullPointerException when the specified key_element is null.
The below programs illustrate the use of java.util.concurrent.ConcurrentHashMap.containsKey() method:
Program 1: This program involves mapping String Values to Integer Keys.
105 is not a key. 100 is a key.
Program 2: This program involves mapping Integer Values to String Keys.
GFG is a key. Geek is not a key.
Please Login to comment...