How to check if a key exists in a HashMap in Java

11 Dec, 2018
Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not.
Examples:
Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2
Output: true

Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10
Output: false

Using Iterator (Not Efficient):Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          // Create a HashMap        HashMap<Integer, String>            map = new HashMap<>();          // Populate the HashMap        map.put(1, "Geeks");        map.put(2, "ForGeeks");        map.put(3, "GeeksForGeeks");          // Get the key to be removed        int keyToBeChecked = 2;          // Print the initial HashMap        System.out.println("HashMap: "                           + map);          // Get the iterator over the HashMap        Iterator<Map.Entry<Integer, String> >            iterator = map.entrySet().iterator();          // flag to store result        boolean isKeyPresent = false;          // Iterate over the HashMap        while (iterator.hasNext()) {              // Get the entry at this iteration            Map.Entry<Integer, String>                entry                = iterator.next();              // Check if this key is the required key            if (keyToBeChecked == entry.getKey()) {                  isKeyPresent = true;            }        }          // Print the result        System.out.println("Does key "                           + keyToBeChecked                           + " exists: "                           + isKeyPresent);    }}Output:HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}
Does key 2 exists: true
Program 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use.// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          try {            // Create a HashMap            HashMap<Integer, String>                map = new HashMap<>();              // Populate the HashMap            map.put(1, "Geeks");            map.put(2, "ForGeeks");            map.put(null, "GeeksForGeeks");              // Get the key to be removed            int keyToBeChecked = 2;              // Print the initial HashMap            System.out.println("HashMap: "                               + map);              // Get the iterator over the HashMap            Iterator<Map.Entry<Integer, String> >                iterator = map.entrySet().iterator();              // flag to store result            boolean isKeyPresent = false;              // Iterate over the HashMap            while (iterator.hasNext()) {                  // Get the entry at this iteration                Map.Entry<Integer, String>                    entry                    = iterator.next();                  // Check if this key is the required key                if (keyToBeChecked == entry.getKey()) {                      isKeyPresent = true;                }            }              // Print the result            System.out.println("Does key "                               + keyToBeChecked                               + " exists: "                               + isKeyPresent);        }        catch (Exception e) {            System.out.println(e);        }    }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
java.lang.NullPointerException
Using HashMap.containsKey method(Efficient):Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          // Create a HashMap        HashMap<Integer, String>            map = new HashMap<>();          // Populate the HashMap        map.put(1, "Geeks");        map.put(2, "ForGeeks");        map.put(null, "GeeksForGeeks");          // Get the key to be removed        int keyToBeChecked = 2;          // Print the initial HashMap        System.out.println("HashMap: "                           + map);          // Check is key exists in the Map        boolean isKeyPresent = map.containsKey(keyToBeChecked);          // Print the result        System.out.println("Does key "                           + keyToBeChecked                           + " exists: "                           + isKeyPresent);    }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
Does key 2 exists: true

Using Iterator (Not Efficient):Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          // Create a HashMap        HashMap<Integer, String>            map = new HashMap<>();          // Populate the HashMap        map.put(1, "Geeks");        map.put(2, "ForGeeks");        map.put(3, "GeeksForGeeks");          // Get the key to be removed        int keyToBeChecked = 2;          // Print the initial HashMap        System.out.println("HashMap: "                           + map);          // Get the iterator over the HashMap        Iterator<Map.Entry<Integer, String> >            iterator = map.entrySet().iterator();          // flag to store result        boolean isKeyPresent = false;          // Iterate over the HashMap        while (iterator.hasNext()) {              // Get the entry at this iteration            Map.Entry<Integer, String>                entry                = iterator.next();              // Check if this key is the required key            if (keyToBeChecked == entry.getKey()) {                  isKeyPresent = true;            }        }          // Print the result        System.out.println("Does key "                           + keyToBeChecked                           + " exists: "                           + isKeyPresent);    }}Output:HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}
Does key 2 exists: true
Program 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use.// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          try {            // Create a HashMap            HashMap<Integer, String>                map = new HashMap<>();              // Populate the HashMap            map.put(1, "Geeks");            map.put(2, "ForGeeks");            map.put(null, "GeeksForGeeks");              // Get the key to be removed            int keyToBeChecked = 2;              // Print the initial HashMap            System.out.println("HashMap: "                               + map);              // Get the iterator over the HashMap            Iterator<Map.Entry<Integer, String> >                iterator = map.entrySet().iterator();              // flag to store result            boolean isKeyPresent = false;              // Iterate over the HashMap            while (iterator.hasNext()) {                  // Get the entry at this iteration                Map.Entry<Integer, String>                    entry                    = iterator.next();                  // Check if this key is the required key                if (keyToBeChecked == entry.getKey()) {                      isKeyPresent = true;                }            }              // Print the result            System.out.println("Does key "                               + keyToBeChecked                               + " exists: "                               + isKeyPresent);        }        catch (Exception e) {            System.out.println(e);        }    }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
java.lang.NullPointerException

Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result.
Get the HashMap and the Key
Create an iterator to iterate over the HashMap using HashMap.iterate() method.
Iterate over the HashMap using the Iterator.hasNext() method.
While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.
If the key matches, set the flag as true.
The flag value after iterating, contains the result.
Below is the implementation of the above approach:
Program 1:
// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          // Create a HashMap        HashMap<Integer, String>            map = new HashMap<>();          // Populate the HashMap        map.put(1, "Geeks");        map.put(2, "ForGeeks");        map.put(3, "GeeksForGeeks");          // Get the key to be removed        int keyToBeChecked = 2;          // Print the initial HashMap        System.out.println("HashMap: "                           + map);          // Get the iterator over the HashMap        Iterator<Map.Entry<Integer, String> >            iterator = map.entrySet().iterator();          // flag to store result        boolean isKeyPresent = false;          // Iterate over the HashMap        while (iterator.hasNext()) {              // Get the entry at this iteration            Map.Entry<Integer, String>                entry                = iterator.next();              // Check if this key is the required key            if (keyToBeChecked == entry.getKey()) {                  isKeyPresent = true;            }        }          // Print the result        System.out.println("Does key "                           + keyToBeChecked                           + " exists: "                           + isKeyPresent);    }}
HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}
Does key 2 exists: true

Program 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use.
// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          try {            // Create a HashMap            HashMap<Integer, String>                map = new HashMap<>();              // Populate the HashMap            map.put(1, "Geeks");            map.put(2, "ForGeeks");            map.put(null, "GeeksForGeeks");              // Get the key to be removed            int keyToBeChecked = 2;              // Print the initial HashMap            System.out.println("HashMap: "                               + map);              // Get the iterator over the HashMap            Iterator<Map.Entry<Integer, String> >                iterator = map.entrySet().iterator();              // flag to store result            boolean isKeyPresent = false;              // Iterate over the HashMap            while (iterator.hasNext()) {                  // Get the entry at this iteration                Map.Entry<Integer, String>                    entry                    = iterator.next();                  // Check if this key is the required key                if (keyToBeChecked == entry.getKey()) {                      isKeyPresent = true;                }            }              // Print the result            System.out.println("Does key "                               + keyToBeChecked                               + " exists: "                               + isKeyPresent);        }        catch (Exception e) {            System.out.println(e);        }    }}
HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
java.lang.NullPointerException

Using HashMap.containsKey method(Efficient):Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          // Create a HashMap        HashMap<Integer, String>            map = new HashMap<>();          // Populate the HashMap        map.put(1, "Geeks");        map.put(2, "ForGeeks");        map.put(null, "GeeksForGeeks");          // Get the key to be removed        int keyToBeChecked = 2;          // Print the initial HashMap        System.out.println("HashMap: "                           + map);          // Check is key exists in the Map        boolean isKeyPresent = map.containsKey(keyToBeChecked);          // Print the result        System.out.println("Does key "                           + keyToBeChecked                           + " exists: "                           + isKeyPresent);    }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
Does key 2 exists: true

Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result.
Get the HashMap and the Key
Check if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.
The flag value, contains the result.
Below is the implementation of the above approach:
Program 1:
// Java program to check if a key exists// in a HashMap or not  import java.util.*;  public class GFG {    public static void main(String[] args)    {          // Create a HashMap        HashMap<Integer, String>            map = new HashMap<>();          // Populate the HashMap        map.put(1, "Geeks");        map.put(2, "ForGeeks");        map.put(null, "GeeksForGeeks");          // Get the key to be removed        int keyToBeChecked = 2;          // Print the initial HashMap        System.out.println("HashMap: "                           + map);          // Check is key exists in the Map        boolean isKeyPresent = map.containsKey(keyToBeChecked);          // Print the result        System.out.println("Does key "                           + keyToBeChecked                           + " exists: "                           + isKeyPresent);    }}
HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
Does key 2 exists: true

Java-Collections
Java-HashMap
Java-Map-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Introduction to Java
Initialize an ArrayList in Java