containsKey()
is a built-in method defined in the HashMap
class in Java. The class is available in the java.util package.
The following is the method prototype:
public boolean containsKey(K key)
HashMaps store data in a key-value pair such that each unique key is mapped onto one or more corresponding values.
We use the containsKey()
method to check whether the passed key is mapped into the HashMap. In other words, the method checks if the given key exists within the HashMap.
The method takes the following as its input argument:
key
: The key being checked within the HashMap.The containsKey()
method returns true
if the specified key is found within the HashMap.
Otherwise, the method returns false
.
import java.util.HashMap;public class Main{public static void main(String args[]){// Creating an empty HashMapHashMap<Integer, String> hash_map = new HashMap<Integer, String>();// Mapping string values to int keyshash_map.put(2, "Edpresso");hash_map.put(4, "Shots");hash_map.put(6, "of");hash_map.put(8, "Dev");hash_map.put(10, "Knowledge");// Displaying the HashMapSystem.out.println("HashMap: \n" + hash_map);// Checking for the Key 10System.out.println("\nContains 10?\n" +hash_map.containsKey(10));// Checking for the Key 11System.out.println("\nContains 11?\n" +hash_map.containsKey(11));}}
Free Resources