Check if a particular key exists in HashMap with Example

II have already shared how HashMap remove () method works internally. In this tutorial we will see how to check if a particular key is present in HashMap. containsKey() method is used to perform this check.

Syntax of the containsKey method :

public boolean containsKey(Object key): According to Oracle docs, returns true if the Map contains the mapping for a specified key.


Check if a particular key exists in HashMap Example



import java.util.*;

 public class ExampleToCheckKey {
    public static void main(String args[]) {
        
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
 
    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Apple");
    hashmap.put(22,"Banana");
    hashmap.put(33,"Mango");
    hashmap.put(44,"Pear");
    hashmap.put(55,"PineApple");
 
    // Checking Key Existence
    boolean flag = hashmap.containsKey(22);
    System.out.println("Key 11 exists in HashMap? : " + flag);
 
    boolean flag2 = hashmap.containsKey(55);
    System.out.println("Key 44 exists in HashMap? : " + flag2);
 
    boolean flag3 = hashmap.containsKey(99);
    System.out.println("Key 88 exists in HashMap? : " + flag3);
    }
}


Output

Key 11 exists in HashMap? : true
Key 44 exists in HashMap? : true
Key 88 exists in HashMap? : false





About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry