Check if a particular key exists in HashMap with Example

In this tutorial, we will see how to check if a particular key is present in HashMap. I have already shared how HashMap remove () method works internally. There are 3 ways to achieve our goal:

1. Using HashMap class containsKey() method

2. Converting HashMap keys to list and then iterating through them

3. Iterating over all the entries of the HashMap by creating a Map

Read Also: Get Value from Key in HashMap with Example

Check if a particular key exists in HashMap with Example

1. Using containsKey() method


We can check if a particular key exists by using HashMap class containsKey() method.

Syntax:

 public boolean containsKey(Object key)


According to Oracle docs, returns true if the Map contains the mapping for a specified key.

Algorithm:

1. Initialize the HashMap, specifying the datatypes of the Key and Value pair.
2. Adding data i.e. key-value pair values using put() method.
3. Check whether the particular key exists or not using containsKey() method and store the boolean  value in a variable.

 import java.util.*;

 public class ExampleToCheckKey {

    public static void main(String args[]) {
        
        // Creating an object of HashMap with Integer keys and String values
        HashMap<Integer, String> map = new HashMap<Integer, String>();
 
        // Putting Key and Value pairs to HashMap
        map.put(100,"Apple");
        map.put(200,"Banana");
        map.put(300,"Mango");
        map.put(400,"Pear");
        map.put(500,"PineApple");
 
        // Checking whether Key exists or not
        boolean result = map.containsKey(100);
        System.out.println("Is Key 100 exists in HashMap: " + result);
 
        boolean result2 = map.containsKey(300);
        System.out.println("Is Key 300 exists in HashMap: " + result2);
 
        boolean result3 = map.containsKey(900);
        System.out.println("Is Key 900 exists in HashMap: " + result3);
    }
}


Output:

Is Key 100 exists in HashMap: true
Is Key 300 exists in HashMap: true
Is Key 900 exists in HashMap: false

2. Iterating through HashMap keys by converting them to list


We can check if a particular key exists by converting HashMap keys to list and then iterating through them.

Algorithm:

1. Instantiate HashMap by specifying the datatypes of Key Value pair.
2. Inserting data into the HashMap by using put() method.
3. Converted HashMap's keys to list by passing keySet() method in the ArrayList constructor.
4. Iterate through the list and check whether it exists or not using ==.

 import java.util.*;

 public class ExampleToCheckKey2 {
    
    public static void main(String args[]) {
        
        // Instantiating HashMap with Integer keys and String values
        HashMap<Integer, String> map2 = new HashMap<Integer, String>();
        boolean result = false; 
        // Inserting Key and Value pairs to HashMap
        map2.put(11,"Book1");
        map2.put(12,"Book2");
        map2.put(13,"Book3");
        map2.put(14,"Book4");
        map2.put(15,"Book5");
 
        // Converting HashMap keys to list 
        ArrayList<Integer> keysList = new ArrayList(map2.keySet());
 
        // Declaration of the iterator
        Iterator it = keysList.iterator();
        
        while( it.hasNext()) {
            // Key to be checked, here 11     
            if((int) it.next() == 11)
                result = true;
        }
 
        System.out.println("Is Key 11 exists in HashMap: " + result);
        
    }
}


Output:

Is Key 11 exists in HashMap: true

3. Creating Map from all the entries present in the Map and then traversing through them


We can check if a particular key exists by creating Map from all the entries present in the Map and then traversing through them.

Algorithm:

1. Repeat steps 1 through 2 mentioned in the second approach to initialize a HashMap.
2. Create a Map by using the for each loop and the entrySet() predefined method of the HashMap class.
3. In each for loop iteration, get a key from the Map using getKey() method.
4. Check whether it is equal to the specified key.
5. Returns true if the key matches

 import java.util.*;

 public class ExampleToCheckKey3 {
    
    public static void main(String args[]) {
        
        // Making an object of HashMap with Integer keys and String values
        HashMap<Integer, String> map3 = new HashMap<Integer, String>();
        boolean result = false; 
        // Pushing Key and Value pairs to HashMap
        map3.put(21,"Car1");
        map3.put(22,"Car2");
        map3.put(23,"Car3");
        map3.put(24,"Car4");
        map3.put(25,"Car5");
 
        // Using foreach loop  
        for(Map.Entry<Integer,String> entry : map3.entrySet()) {
            // Key to be checked here is 21 
            if((int) entry.getKey() == 21)
                result = true;
        }
        System.out.println("Is Key 21 exists in HashMap: " + result);
    }
}


Output:

Is Key 21 exists in HashMap: true

That's all for today. Please mention in the comments if you have any questions related to how to check if particular key exists in HashMap.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry