Java HashMap containsKey()

The syntax of the containsKey() method is:

hashmap.containsKey(Object key)

Here, hashmap is an object of the HashMap class.


containsKey() Parameter

The containsKey() method takes a single parameter.

  • key - mapping for the key is checked in the hashmap

containsKey() Return Value

  • returns true if the mapping for the specified key is present in the hashmap
  • returns false if the mapping for the specified key is not present in the hashmap

Example 1: Java HashMap containsKey()

import java.util.HashMap;

class Main {
  public static void main(String[] args){

    // create a HashMap
    HashMap<String, String> details = new HashMap<>();

    // add mappings to HashMap
    details.put("Name", "Programiz");
    details.put("Domain", "programiz.com");
    details.put("Location", "Nepal");
    System.out.println("Programiz Details: \n" + details);

    // check if key Domain is present
    if(details.containsKey("Domain")) {
      System.out.println("Domain name is present in the Hashmap.");
    }

  }
}

Output

Programiz Details: 
{Domain=programiz.com, Name=Programiz, Location=Nepal}
Domain name is present in the Hashmap.

In the above example, we have created a hashmap. Notice the expressions,

details.containsKey("Domain") // returns true

Here, the hashmap contains a mapping for the key Domain. Hence, the containsKey() method returns true and statement inside if block is executed.


Example 2: Add Entry to HashMap if Key is already not present

import java.util.HashMap;

class Main {
  public static void main(String[] args){

    // create a HashMap
    HashMap<String, String> countries = new HashMap<>();

    // add mappings to HashMap
    countries.put("USA", "Washington");
    countries.put("Australia", "Canberra");
    System.out.println("HashMap:\n" + countries);

    // check if key Spain is present
    if(!countries.containsKey("Spain")) {
      // add entry if key already not present
      countries.put("Spain", "Madrid");
    }

    System.out.println("Updated HashMap:\n" + countries);

  }
}

Output

HashMap:
{USA=Washington, Australia=Canberra}
Updated HashMap:
{USA=Washington, Australia=Canberra, Spain=Madrid}

In the above example, notice the expression,

if(!countries.containsKey("Spain")) {..}

Here, we have used the containsKey() method to check if a mapping for Spain is present in the hashmap. Since we have used the negate sign (!), the if block is executed if the method returns false.

Hence, the new mapping is added only if there is no mapping for the specified key in the hashmap.

Note: We can also use the HashMap putIfAbsent() method to perform the same task.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges