Java HashMap - containsKey() Method
The java.util.HashMap.containsKey() method returns true if this map contains a mapping for the specified key.
Syntax
public boolean containsKey(Object key)
Parameters
key |
Specify the key whose presence in this map is to be tested. |
Return Value
Returns true if this map contains a mapping for the specified key.
Exception
NA.
Example:
In the example below, the java.util.HashMap.containsKey() method is used to check the presence of specified key in the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a hash map HashMap<Integer, String> MyMap = new HashMap<Integer, String>(); //populating MyMap MyMap.put(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); MyMap.put(104, "Jo"); //check the presence of 103 key System.out.print("Does MyMap contain 103 key? - "); System.out.print(MyMap.containsKey(103)); //check the presence of 105 key System.out.print("\nDoes MyMap contain 105 key? - "); System.out.print(MyMap.containsKey(105)); } }
The output of the above code will be:
Does MyMap contain 103 key? - true Does MyMap contain 105 key? - false
❮ Java.util - HashMap