Site icon JavaGoal

How to check the map contains key by hashmap containskey() method

We have learned a lot of things about HashMap in java and the internal working of HashMap. Here we will learn how to check the given key is presented in HashMap or not. The hashmap containskey() method is used to check whether the map contains key or not? Let’s see the containskey() java.

containsKey(Object key) method

This method is used to check whether the specified key exists in HashMap or not. It returns type is boolean. If the given key exists in HashMap, then it returns true otherwise false.

Where, Key is the key with which the specified value(V) is to be associated in HashMap.
return type:  Its return type is boolean. It can return either true or false.

Let’s see the hashmap containskey() method example

import java.util.HashMap;
public class ExampleOfHashMap 
{
    public static void main(String[] args) 
    {
        HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
        
        // Adding objects in HashMap
        hashMap.put(1, "JavaGoal.com");
        hashMap.put(2, "Learning");
        hashMap.put(3, "Website");
        
        System.out.println("Is key 1 exists: "+hashMap.containsKey(1));
        System.out.println("Is key 5 exists: "+hashMap.containsKey(5));
    }
}

Output: Is key 1 exists: true
Is key 5 exists: false

Exit mobile version