How to Check if a Key Object Exists in HashMap Java? containsKey() Example

Hello guys, you might know that one of the common programming tasks 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 programmers write code like below which is not correct, which inspired 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 because HashMap does allow null values.

Many Java programmers will test this code for some valid input and think that it's working fine, only to create a subtle bug in production.  That's why it's always better to write extensive JUnit tests for your code to test positive, negative and boundary conditions.

Another suggestion I want to make is that it's always better to use an API method if it can do the job, not just me but many greats have also advised this. The great Java programmer Joshua Bloch even included a chapter on this on his all-time great Java book Effective Java, a must-read book for any Java programmer.

The biggest advantage of using an API method is that it has already tried and tested by many programmers and faced many inputs and conditions which is impossible for your own code to execute. This benefit of testing exposure really helps when you put your code into production.

I also suggest all programmers go through a comprehensive book or course like The Complete Java Masterclass on Udemy to fill the gaps in your learning because Java is vast and there is always a better way to do things.




How do HashMap checks if a key object exists or not

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 retrieves the value from it and returns 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, sees my post how does get() and put() works in Java, for a detailed discussion on this topic. 

How to check if a key exists in HashMap in Java



Though, if you are not familiar with Java Collection framework, I suggest you go through Java Fundamentals: Collections course on Pluaralsight.  One of the better course to master this important part of Java API.



How to check if a given 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, it's an anti-pattern but you can use it if your Map is not too big. Later, I have asked the user to enter a key in command prompt, which you can check against this HashMap.

Our program reads input from the command prompt using Scanner class and uses containsKey() to check if a given key exists or not.  If the key exists then this method will return true otherwise it will return false. Accordingly, our program will print whether a given key exists in the HashMap or not.

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 an 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 looks for an entry object corresponding to the given key, which means it also handles null values properly. 

 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 like. HashMap, TreeMap, and LinkedHashMap. Why? because this method is defined in java.util.Map interface and every map implementation are supposed to implement it.


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 like TreeMap, LinkedHashMap, Hashtable, EnumMap etc.

Further Learning
The Complete Java Masterclass
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java

Other Java Collection tutorials you may like
How to sort a Map by keys and values in Java? (tutorial)
The difference between HashMap and LinkedHashMap in Java? (answer)
The difference between Hashtable and HashMap in Java? (answer)
The difference between HashMap and ConcurrentHashMap in Java? (answer)
The difference between ArrayList and LinkedList in Java? (answer)
The difference between Vector and ArrayList in Java? (answer)
Difference between EnumMap and HashMap in Java
The difference between HashSet and TreeSet in Java? (answer)
How to remove a key-value pair from HashMap in Java? (tutorial)
How to sort a HashMap by keys in Java 8? (tutorial)

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or feedback then please drop a comment

2 comments:

  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