Thursday, September 21, 2023

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

Hello Java programmers, if you have working in Java programming language or writing server side programs then you may 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 JDK API well, all you need to is call the containsKey() method, it returns true if the 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 exists 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 been 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 that shows how HashMap is structured internally on an array, called a bucket. When you call the get() method, it gets the bucket location by applying a hash function on the key and then checking if an entry is stored there or not, if no entry then it returns null, which means the 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 on 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 the Java Collection framework, I suggest you go through Java Fundamentals: Collections course on Pluralsight.  One of the better courses 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 the 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 the 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 the command prompt, which you can check against this HashMap.

Our program reads input from the command prompt using the 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 the 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.


That's all about how to check if a key exists in HashMap in Java or not. You can also use the containsValue() method to check if the 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.


Other Java Collection tutorials you may like
  • How to sort a Map by keys and values in Java? (tutorial)
  • 7 Best Courses to learn Java Collection Framework (best courses)
  • The difference between HashMap and LinkedHashMap in Java? (answer)
  • 10 Advanced Core Java courses for experienced (advanced courses)
  • The difference between Hashtable and HashMap in Java? (answer)
  • Top 5 Java Programming Courses for Beginners (online courses)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • 10 Free Data Structure and Algorithms Courses (free courses)
  • 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 (answer)
  • 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 Java article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment

P. S. - If you are new to the Java programming world and looking for a free online course to learn Java in-depth then I highly recommend you to check out this Java Tutorial for Complete Beginners (FREE) course on Udemy. More than 1 million students have already joined this course. 

Now, is the quiz time, what is difference between HashMap and ConcurrentHashMap in Java? Can you pass an HashMap to a method which expect a ConcurrentHashMap?

5 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
  2. can you please do an example when key is an Object type, instead of primitive type

    ReplyDelete
    Replies
    1. Hello buddhi, string is an object, not a primitive type? Do you mean a user generated class like Employee?

      Delete
  3. Thanks for sharing. It is really helpful.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.