How to check if a key exists in HashMap Java? Use containsKey()

One of the common programming task while using HashMap in Java is to check if a given key exists in the map or not. This is supposed to be easy, right? Yes, it is easy if you know your API well, all you need to is call the containsKey() method, it returns true if given key exists in HashMap, otherwise false; but I have seen many programmer's codes like we will see in this article, which prompted me to write this blog post.

if(map.get(key) !=  null){
    System.out.println("key exits in Map");
}

This code is fragile, it will not work if you have added null values into HashMap, remember HashMap does allow null values. Many programers will test this code for some input and think that it's working fine, only to create a subtle bug in production.  It's always better to use an API method if it can do the job, many greats have advised this. Joshua Bloch even included a chapter on his classic book Effective Java, a must-read book for any Java programmer.



How to check if a key exists in HashMap in Java

Here is our sample program to demonstrate how you can use containsKey() method to check if a given key exists in HashMap or not. In this example, we have first created a HashMap with values using double brace initialization technique. Later, I have asked the user to enter a key in command prompt.



Our program reads input from the command prompt using Scanner class and uses containsKey() to check if given key exists or not. If the key exists then this method will return true otherwise false.

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

/**
 * Java Program to to check if a key exists in HashMap or not. 
 * This example uses containsKey() method to search for a key in HashMap.
 *
 * @author WINDOWS 8
 */
public class KeySearchDemo {

    public static void main(String args[]) {

        // our sample map 
        Map<Integer, String> idToName = new HashMap<Integer, String>() {
            {
                put(101, "Johnny");
                put(102, "Root");
                put(103, "Shane");
            }
        };

        System.out.println(idToName);

        // checking if a key exists in Map
        Scanner scnr = new Scanner(System.in);

        System.out.println("Please enter a key to check in Map?");
        int key = scnr.nextInt();

        // checking if key exists in HashMap
        if (idToName.containsKey(key)) {
            System.out.println("Congrats, given key exits in Map");
        } else {
            System.out.println("Sorry, given key doesn't exists in Map");
        }       

        scnr.close();

    }

}

Output :
{101=Johnny, 102=Root, 103=Shane}
Please enter a key to check in Map?
101
Congrats, given key exists in Map

You can see that containsKey() method has returned true for existing key. If you pass any key which is not present in Map then this method will return false. If you look at the code of this method from HashMap.java class on JDK, you will find that it look for an entry object corresponding to the given key, which means it also handles null values. 

 public boolean containsKey(Object key) {
        return getEntry(key) != null;
  }

You can use this technique to verify if a key exists or not in any Map e.g. HashMap, TreeMap, and LinkedHashMap. Why? because this method is defined in java.util.Map interface and every map implementation are supposed to implement it. 

Here is a diagram which shows how HashMap is structured internally on an array, called bucket. When you call get() method, it gets the bucket location by applying a hash function on key and then check if an entry is stored there or not, if no entry then it returns null, which means key doesn't exist in Map. If there is an entry then it retrieve the value from it and return that. Though it's also possible that there are multiple entries in that bucket location due to the hash collision, in that case, it goes through all entries to find the right one. So it's far from easy, see my post how get() and put() works in Java, for a detailed discussion on this topic. 

How to check if a key exists in HashMap in Java


That's all about how to check if a key exists in HashMap in Java or not. You can also use containsValue() method to check if given value exists in Map or not. Similarly, this technique can also be used to check if a given key is present or not in any Map implementation. 


Further Reading
Java Collection framework is very important for all Java developers if you are serious to improve you know knowledge on this key area then don't forget to read Java Generics and Collection by Maurice Naftalin. 


1 comment:

  1. Very informative post! Thanks a lot. Does the time to check whether a key exits by using containsKey() remains constant when Map grows in size?

    ReplyDelete