Java HashMap containsKey() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, containsKey(key) returns true if a HashMap has a mapping for key, and false otherwise. It does not look at the value at all.

Like get, it hashes the key and checks one bucket, so it is fast on average. It answers a question get cannot: whether a key is stored with a null value or not stored at all.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety.

Syntax

Pass the key; you get a boolean.

Java
Map<String, String> phones = new HashMap<>();
phones.put("Asha", "555-0101");
boolean a = phones.containsKey("Asha");   // true
boolean b = phones.containsKey("asha");   // false (case-sensitive)
CallWhat it does
map.containsKey(k)true if k has a mapping.
map.containsKey(null)true if a null key is stored.
!map.containsKey(k)The key is missing.
map.keySet().contains(k)Same answer through the key view.

Checking containsKey and then calling get does two lookups. When null values are impossible in your map, a single get plus a null check is enough.

Library declarations
Java
// java.util.HashMap<K, V>
public boolean containsKey(Object key)

// Declared in Map<K, V>

Parameters

ParameterDescription
key (Object)The key to test. May be null.

Return Value

Return ValueDescription
booleantrue if the map contains a mapping for key; otherwise false.

Compare with Similar Methods

Presence checks and lookups:

MethodHow it differs
containsValue(v)Searches the values instead; much slower, it checks every entry.
get(k)Returns the value, but null is ambiguous.
putIfAbsent(k, v)Checks and inserts in one call.

Java Examples

Example 1 — Check a Phone Book Before Reading It

A phone book where one person is listed without a number.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapContainsKeyDemo {
    public static void main(String[] args) {
        Map<String, String> phoneBook = new HashMap<>();
        phoneBook.put("Asha", "555-0101");
        phoneBook.put("Ben", "555-0199");
        phoneBook.put("Cara", null);

        String[] names = {"Ben", "Cara", "Dev"};
        for (String name : names) {
            if (phoneBook.containsKey(name)) {
                System.out.println(name + ": listed, number = " + phoneBook.get(name));
            } else {
                System.out.println(name + ": not in the phone book");
            }
        }
    }
}

How It Works

  1. Listed with a number. Ben is a key, so the check passes and get prints his number.
  2. Listed without a number. Cara's key exists even though her value is null, so containsKey still returns true.
  3. Not listed. Dev was never added, so the else branch runs; with get alone, Cara and Dev would both look like null.
  4. Keys only. The method never inspects the phone numbers themselves; it answers purely from the set of keys.

Example 2 — Custom Keys Need equals() and hashCode()

Two seat classes with the same fields: one overrides equals and hashCode, the other does not.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class HashMapContainsKeyCustom {
    static class Seat {
        final char row;
        final int number;

        Seat(char row, int number) {
            this.row = row;
            this.number = number;
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Seat)) {
                return false;
            }
            Seat s = (Seat) o;
            return row == s.row && number == s.number;
        }

        @Override
        public int hashCode() {
            return Objects.hash(row, number);
        }
    }

    static class RawSeat {
        final char row;
        final int number;

        RawSeat(char row, int number) {
            this.row = row;
            this.number = number;
        }
    }

    public static void main(String[] args) {
        Map<Seat, String> booked = new HashMap<>();
        booked.put(new Seat('B', 7), "Mia");

        Map<RawSeat, String> rawBooked = new HashMap<>();
        rawBooked.put(new RawSeat('B', 7), "Mia");

        System.out.println("Seat B7 booked? " + booked.containsKey(new Seat('B', 7)));
        System.out.println("Seat B8 booked? " + booked.containsKey(new Seat('B', 8)));
        System.out.println("RawSeat B7 booked? " + rawBooked.containsKey(new RawSeat('B', 7)));
    }
}

How It Works

  1. Value-based key. Seat defines equality by row and number and builds its hash from the same two fields with Objects.hash.
  2. New object, same seat. The lookup creates a fresh Seat('B', 7); it lands in the same bucket and equals says it matches, so the answer is true.
  3. Different seat. B8 differs in its number, so no stored key is equal to it.
  4. Identity fallback. RawSeat inherits Object.equals, which only matches the very same object, so even an identical-looking seat is reported as not booked.

Example 3 — Validate Orders Against a Menu

Normalize each order to lower case, add up the prices of items on the menu, and skip the rest.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapContainsKeyMenu {
    public static void main(String[] args) {
        Map<String, Integer> menu = new HashMap<>();
        menu.put("tea", 30);
        menu.put("coffee", 45);
        menu.put("cake", 60);

        String[] orders = {"coffee", "Tea", "cake", "soup"};
        int bill = 0;
        for (String item : orders) {
            String key = item.toLowerCase();
            if (menu.containsKey(key)) {
                bill += menu.get(key);
                System.out.println("added " + key);
            } else {
                System.out.println("skipped " + item + " (not on the menu)");
            }
        }
        System.out.println("bill = " + bill);
        System.out.println("containsKey(\"Tea\") = " + menu.containsKey("Tea"));
    }
}

How It Works

  1. Normalize first. Orders are converted with toLowerCase() so "Tea" matches the stored key "tea".
  2. Guard the unboxing. Prices are added only after containsKey confirms the item, so menu.get(key) never returns null into bill +=.
  3. Reject unknown items. "soup" is not a key, so it is reported and contributes nothing: 45 + 30 + 60 = 135.
  4. Raw key is case-sensitive. The final line shows that without normalizing, "Tea" is not found.

Frequently Asked Questions

Call map.containsKey(key). It returns true when the key has a mapping, even if the value is null.
They differ only for keys mapped to null: containsKey() returns true, while get() returns null as if the key were missing.
Yes. String.equals is case-sensitive, so "Tea" and "tea" are different keys. Normalize the case before storing and looking up.
The class probably does not override equals() and hashCode(). Without them, only the exact same object is found.
Constant time on average, like get(), because only one bucket is examined.

Next: containsValue()

Check whether any key maps to a value.

containsValue() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful