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.

What does the containsKey() method do?

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.

hashmap containskey method example

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.

hashmap containskey() method example

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

Frequently Asked Questions

What does the containsKey() method return?

As described above, containsKey(Object key) has a boolean return type. It returns true if the given key exists in the HashMap, and false otherwise.

What parameter does containsKey() accept?

It accepts the key to be checked against the map. In the example on this page, the keys are Integer values such as 1 and 5.

How is containsKey() used in the example on this page?

The example creates a HashMap, adds entries with put(), and then calls containsKey(1) and containsKey(5). The output shows true for key 1 and false for key 5.

Where can I learn more about HashMap in Java?

See the related JavaGoal articles on HashMap in java, the internal working of HashMap, and the HashMap methods.

1 thought on “How to check the map contains key by hashmap containskey() method”

  1. Hello everyone, it’s my first go to see at this website, and post is truly fruitful in support of me, keep
    up posting these types of posts.

    Reply

Leave a Comment