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): Returnstrueif the key exists, otherwisefalse.
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 fornullcan be unreliable if the value stored is actuallynull. - Not considering the key type carefully; keys must match exactly in type and value.
- Confusing
containsKey()withcontainsValue(), 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:
| Method | Description | Returns |
|---|---|---|
| containsKey(key) | Checks if the key exists in the map | true or false |
| get(key) | Returns the value for the key or null if missing | Value or null |
| containsValue(value) | Checks if a value exists in the map | true 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.