Press "Enter" to skip to content

HashMap containsKey() Method in Java

The containsKey(K key) method of HashMap checks if the map contains a specified key or not. It returns true if the map contains the specified key otherwise returns false. Some implementations of map throw NullPointerException if the key is null.

As HashMap supports null key. So, we can use this method safely with a null key.

Syntax

boolean containsKey(K key)
Freshers Placement

Parameter

The key to check its presence in the map

Program

import java.util.HashMap;
import java.util.Map;

public class HashMapContainsKeyExample {

    public static void main(String[] args) {

        Map < Integer, String > map = new HashMap < > ();
        map.put(101, "John");
        map.put(102, "Adam");
        map.put(103, "Ricky");
        map.put(104, "Chris");

        boolean is101Present = map.containsKey(101);
        boolean is109Present = map.containsKey(109);
        boolean isNullPresent = map.containsKey(null);

        System.out.println("Map elements: " + map);
        System.out.println("Is key 101 present?: " + is101Present);
        System.out.println("Is key 109 present?: " + is109Present);
        System.out.println("Is null key present?: " + isNullPresent);
    }
}

Output

Map elements: {101=John, 102=Adam, 103=Ricky, 104=Chris}
Is key 101 present?: true
Is key 109 present?: false
Is null key present?: false

Explanation

  • Create a new HashMap
  • Add keys and values to it
  • Check if the map contains the key using the containsKey method
  • When we passed 101 then the containsKey method returned true, for 109 it returned false
  • Finally, the call to the method with null key returned false

Comments are closed.