What is the containsKey method in Java HashMaps?

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)

Functionality

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 containsKey() method

Parameters and return

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.

Code

import java.util.HashMap;
public class Main{
public static void main(String args[]){
// Creating an empty HashMap
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
// Mapping string values to int keys
hash_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 HashMap
System.out.println("HashMap: \n" + hash_map);
// Checking for the Key 10
System.out.println("\nContains 10?\n" +
hash_map.containsKey(10));
// Checking for the Key 11
System.out.println("\nContains 11?\n" +
hash_map.containsKey(11));
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved