Open In App

Check if Particular Key Exists in Java HashMap

Improve
Improve
Like Article
Like
Save
Share
Report

HashMap in Java is the realization of the Hash Table data structure of sorts. It is composed of Key and Value pairs which are symbolically represented as <K,V> where K stands for Key and V for Value. It is an implementation of the Maps Interface and is advantageous in the ways that it provides constant-time performance in assigning and accessing elements via the put and get methods respectively. It is used to form associated pairs and access or modify one based on the other. 

There are various approaches to check if particular key exists which are mentioned below :

  • Using the built-in containsKey() method of the HashMap class
  • Converting the keys of the HashMap to a list and then iterating through them
  • Creating a Map from all the entries of the HashMap and then iterating over it

Approach 1 :

Using this approach, we make use of the containsKey() predefined method of the HashMap class which returns a boolean value.

Syntax:

Hash_Map.containsKey(key_element)

Parameters: The method takes just one parameter key_element that refers to the key whose mapping is supposed to be checked inside a map.

Return Value: The method returns boolean true if the presence of the key is detected else false

Algorithm :

  1. Create a function with a return type of boolean.
  2. Inside the function, create a new HashMap specifying the data types of the key and the value respectively.
  3. Fill up the HashMap with Key-Value Pairs using the put() method of the HashMap class.
  4. Declare a boolean variable to store the result.
  5. Call the containsKey() method of the HashMap class with the key to be checked as the parameter.
  6. Return the variable.

Code :

Java




// java program to check if a particular
// key exists in HashMap
 
import java.util.*;
 
class GFG {
 
    // declaring the method
    // the parameter keyToBeChecked is the
    // key to be checked
    boolean checkForKey(String keyToBeChecked)
    {
 
        // initializing the hashmap
        HashMap<String, Integer> hashMap =
          new HashMap<>();
 
        // filling the key - value pairs in hashmap
        hashMap.put("first", 1);
        hashMap.put("second", 2);
        hashMap.put("third", 3);
        hashMap.put("fourth", 4);
 
        // variable to store the boolean value
        // for result
        boolean result
            = hashMap.containsKey(keyToBeChecked);
 
        // returning the result
        return result;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // displaying and calling the checkForKey()
        // method
        System.out.println(ob.checkForKey("fourth"));
    }
}


Output

true

Approach 2 :

We create an ArrayList from the keys of the HashMap and then iterate over them to check if the specified key is present or not.

Algorithm : 

  1. Repeat steps 1 through 3 as mentioned in the first approach.
  2. Next, we initialize an ArrayList of the same data type as the keys of the HashMap using the keySet() predefined method of the HashMap class.
  3. For the next step, we declare an iterator to iterate through the elements of the ArrayList created above.
  4. We then iterate through the ArrayList checking in each iteration if the particular key matches with any of the elements of the ArrayList created above.
  5. Return the corresponding output.

Code :

Java




// java program to check if a particular
// key exists in the HashMap
 
import java.util.*;
 
class GFG {
 
    // declaring the method
    // the parameter keyToBeChecked is
    // the key to be checked
    boolean checkForKey(String keyToBeChecked)
    {
 
        // initializing the HashMap
        HashMap<String, Integer> hashMap =
          new HashMap<>();
 
        // filling the key-value pairs
        // in the HashMap
        hashMap.put("first", 1);
        hashMap.put("second", 2);
        hashMap.put("third", 3);
        hashMap.put("fourth", 4);
 
        // creating an ArrayList from the keys
        ArrayList<String> listOfKeys
            = new ArrayList<>(hashMap.keySet());
 
        // declaring the iterator
        Iterator<String> itr = listOfKeys.iterator();
 
        // loop to iterate through the
        // elements of the ArrayList
        while (itr.hasNext()) {
 
            // condition to check against
            // the specific key
            if (itr.next() == keyToBeChecked)
                return true;
        }
        return false;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // displaying and calling the
        // checkForKey method
        System.out.println(ob.checkForKey("second"));
    }
}


Output

true

Approach 3 :

We iterate over the keys checking if the specified one is present or not.

Algorithm : 

  1. Repeat steps 1 through 3 in the first approach to create a HashMap.
  2. Using a for each loop and the entrySet() predefined method of the HashMap class, create a Map of the same.
  3. In each iteration of the for loop, get a key from the Map built above using the built-in getKey() method of the Map class.
  4. Compare it with the specified key.
  5. Return true if the key matches with any of the elements of the key set or else return false.

Code : 

Java




// java program to check if a particular
// key exists in the HashMap
 
import java.util.*;
 
class GFG {
 
    // declaring the method
    // the parameter keyToBeChecked specifies
    // the particular key
    boolean checkForKey(String keyToBeChecked)
    {
 
        // initializing the HashMap
        HashMap<String, Integer> hashMap = new HashMap<>();
 
        // filling up the key-value
        // pairs in the HashMap
        hashMap.put("first", 1);
        hashMap.put("second", 2);
        hashMap.put("third", 3);
        hashMap.put("fourth", 4);
 
        // initializing the for each loop
        // using which the entries of the
        // HashMap are stored in a Set
        for (Map.Entry<String, Integer> mapEntries :
             hashMap.entrySet()) {
 
            // getting the keys and checking
            // against the specified key
            if (mapEntries.getKey() == keyToBeChecked)
                return true;
        }
        return false;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // displaying and calling the
        // checkForKey method
        System.out.println(ob.checkForKey("seventh"));
    }
}


Output

false

 



Last Updated : 20 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads