Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is the containsKey method in Java HashMaps?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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));
}
}

RELATED TAGS

java

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring