Java Map containsKey(): Check if a Key Exists
- containsKey() correctly returns true when the key exists regardless of whether the value is null. map.get(key) != null is NOT equivalent when null values are possible.
- getOrDefault(key, fallback) is the modern alternative to containsKey() + get() β it's one lookup instead of two.
- computeIfAbsent(key, mappingFunction) adds the key if absent and returns the value β eliminates the check-then-put pattern.
containsKey() is simple but has a couple of edge cases that produce bugs in production code. The main one: map.get(key) != null is NOT equivalent to map.containsKey(key). If the map contains the key with a null value, get() returns null but containsKey() returns true. When you need to distinguish 'key exists with null value' from 'key doesn't exist', you must use containsKey().
containsKey() Usage and Edge Cases
package io.thecodeforge.collections; import java.util.HashMap; import java.util.Map; public class MapContainsKeyExample { public static void main(String[] args) { Map<String, String> serviceRegistry = new HashMap<>(); serviceRegistry.put("PaymentService", "https://payment.thecodeforge.io"); serviceRegistry.put("AuditService", null); // registered but no URL yet // containsKey() β correct way to check key existence System.out.println(serviceRegistry.containsKey("PaymentService")); // true System.out.println(serviceRegistry.containsKey("AuditService")); // true β key exists, value is null System.out.println(serviceRegistry.containsKey("OrderService")); // false // get() != null β WRONG way when null values are possible System.out.println(serviceRegistry.get("AuditService") != null); // false β but key EXISTS! // This is the bug: AuditService is registered but get() returns null // Using get() != null treats it as 'not registered' // Modern alternatives (Java 8+) // getOrDefault β return fallback if key absent String url = serviceRegistry.getOrDefault("OrderService", "http://default.thecodeforge.io"); System.out.println(url); // http://default.thecodeforge.io // computeIfAbsent β add key if absent, return computed value serviceRegistry.computeIfAbsent("OrderService", k -> "https://" + k.toLowerCase() + ".io"); System.out.println(serviceRegistry.get("OrderService")); // https://orderservice.io // putIfAbsent β add only if key not already present serviceRegistry.putIfAbsent("PaymentService", "http://changed-url.io"); // Not overwritten System.out.println(serviceRegistry.get("PaymentService")); // https://payment.thecodeforge.io // containsKey with null key (HashMap allows, not all Maps do) serviceRegistry.put(null, "null-key-service"); System.out.println(serviceRegistry.containsKey(null)); // true (HashMap only) } }
true
false
false
http://default.thecodeforge.io
https://orderservice.io
https://payment.thecodeforge.io
true
| Expression | Returns true when | Returns false when |
|---|---|---|
| containsKey(k) | Key k exists (value may be null) | Key k is not in the map |
| get(k) != null | Key k exists AND value is not null | Key k absent OR value is null |
| getOrDefault(k, d) | Always returns a value | N/A β returns default if absent |
| computeIfAbsent(k, f) | Always returns mapped value | N/A β computes and stores if absent |
π― Key Takeaways
- containsKey() correctly returns true when the key exists regardless of whether the value is null. map.get(key) != null is NOT equivalent when null values are possible.
- getOrDefault(key, fallback) is the modern alternative to containsKey() + get() β it's one lookup instead of two.
- computeIfAbsent(key, mappingFunction) adds the key if absent and returns the value β eliminates the check-then-put pattern.
- Null key support varies by Map implementation: HashMap allows one null key, TreeMap and ConcurrentHashMap throw NullPointerException.
β Common Mistakes to Avoid
- βUsing map.get(key) != null as a null check when the map may contain null values β this incorrectly treats 'key with null value' as 'absent key'. Use containsKey() when null values are possible.
- βChecking containsKey() then immediately calling get() separately β this is two lookups. Use getOrDefault() or computeIfAbsent() for atomic check-and-return.
- βCalling containsKey(null) on a TreeMap or ConcurrentHashMap β TreeMap throws NullPointerException for null keys, and ConcurrentHashMap does too. Only HashMap allows null keys.
Interview Questions on This Topic
- QWhat is the difference between map.containsKey(k) and map.get(k) != null?
- QWhat does computeIfAbsent() do and when would you use it over containsKey() + put()?
Frequently Asked Questions
What is the difference between Map.containsKey() and Map.get() != null in Java?
containsKey() returns true if the key exists in the map, even if its value is null. get(key) != null returns false when the key exists with a null value, treating it the same as an absent key. If your map can contain null values, always use containsKey() to check key existence.
How do I check if a key exists in a Java Map without calling get() twice?
Use getOrDefault(key, defaultValue) to get the value or a fallback in one call. Use computeIfAbsent(key, function) to get-or-compute-and-store in one atomic operation. Both avoid the check-then-act pattern that requires two separate map lookups.
Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.