Java HashMap containsKey(Object key) Method Example

The containsKey(Object key) method of java.util.HashMap class returns true if this map contains a mapping for the specified key.

Signature

public boolean containsKey(Object key)

This method returns true if this map contains a mapping for the specified key.

Example

The following example shows the usage of java.util.HashMap.containsKey(key) method.

import java.util.HashMap;

public class DescendingIteratorMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String>  hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
        
        //Check if the hashmap1 contains key "2"
        System.out.println("Does \"hashMap1\" contains key \"2\" : "+hashMap1.containsKey(2));
    }
}

Output

Does "hashMap1" contains key "2" : true

Leave a Reply

Your email address will not be published. Required fields are marked *