0
0
JavaHow-ToBeginner · 3 min read

How to Check if Key Exists in HashMap in Java

To check if a key exists in a HashMap in Java, use the containsKey(key) method. It returns true if the key is present and false if not.
📐

Syntax

The containsKey() method is called on a HashMap object and takes one argument: the key you want to check. It returns a boolean value.

  • hashMap.containsKey(key): Returns true if the key exists, otherwise false.
java
boolean containsKey(Object key)
💻

Example

This example shows how to create a HashMap, add some key-value pairs, and check if certain keys exist using containsKey().

java
import java.util.HashMap;

public class CheckKeyExample {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("apple", 10);
        map.put("banana", 20);
        map.put("orange", 30);

        System.out.println("Does key 'apple' exist? " + map.containsKey("apple"));
        System.out.println("Does key 'grape' exist? " + map.containsKey("grape"));
    }
}
Output
Does key 'apple' exist? true Does key 'grape' exist? false
⚠️

Common Pitfalls

Some common mistakes when checking keys in a HashMap include:

  • Using get(key) and checking for null can be unreliable if the value stored is actually null.
  • Not considering the key type carefully; keys must match exactly in type and value.
  • Confusing containsKey() with containsValue(), which checks values instead of keys.
java
import java.util.HashMap;

public class PitfallExample {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("key1", null);

        // Wrong way: get() returns null for missing key or null value
        if (map.get("key2") != null) {
            System.out.println("Key exists (wrong check)");
        } else {
            System.out.println("Key does not exist or value is null (wrong check)");
        }

        // Right way: use containsKey()
        if (map.containsKey("key1")) {
            System.out.println("Key exists (correct check)");
        } else {
            System.out.println("Key does not exist (correct check)");
        }
    }
}
Output
Key does not exist or value is null (wrong check) Key exists (correct check)
📊

Quick Reference

Use this quick reference to remember how to check keys in a HashMap:

MethodDescriptionReturns
containsKey(key)Checks if the key exists in the maptrue or false
get(key)Returns the value for the key or null if missingValue or null
containsValue(value)Checks if a value exists in the maptrue or false

Key Takeaways

Use containsKey(key) to reliably check if a key exists in a HashMap.
Avoid using get(key) == null to check keys because values can be null.
containsKey() returns a boolean indicating presence of the key.
Keys must match exactly in type and value to be found.
containsValue() checks values, not keys, so don't confuse them.