Homeβ€Ί Javaβ€Ί Java Map containsKey(): Check if a Key Exists

Java Map containsKey(): Check if a Key Exists

Where developers are forged. Β· Structured learning Β· Free forever.
πŸ“ Part of: Collections β†’ Topic 21 of 21
Learn how to use Java Map.
πŸ§‘β€πŸ’» Beginner-friendly β€” no prior Java experience needed
In this tutorial, you'll learn:
  • 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.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
⚑ Quick Answer
containsKey() answers: is this key registered in the map? It doesn't tell you what the value is, and it doesn't distinguish between a key mapped to null vs a key that doesn't exist. For most maps that's fine β€” but in maps where null values are legitimate, the distinction matters.

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

MapContainsKeyExample.java Β· JAVA
12345678910111213141516171819202122232425262728293031323334353637383940
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)
    }
}
β–Ά Output
true
true
false
false
http://default.thecodeforge.io
https://orderservice.io
https://payment.thecodeforge.io
true
ExpressionReturns true whenReturns false when
containsKey(k)Key k exists (value may be null)Key k is not in the map
get(k) != nullKey k exists AND value is not nullKey k absent OR value is null
getOrDefault(k, d)Always returns a valueN/A β€” returns default if absent
computeIfAbsent(k, f)Always returns mapped valueN/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.

πŸ”₯
Naren Founder & Author

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.

← PreviousJava Stream filter(): Filter Collections with Lambdas
Forged with πŸ”₯ at TheCodeForge.io β€” Where Developers Are Forged