JavaData StructuresBeginner

HashMap.containsKey()

Checks if the HashMap contains a mapping for the specified key.

Review the syntaxStudy the examplesOpen the coding app
boolean HashMap.containsKey(Object key)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Checks if the HashMap contains a mapping for the specified key.

The `containsKey()` method in Java's `HashMap` is used to determine if the map contains an entry for a given key. It returns `true` if the key exists in the map, and `false` otherwise. This method is highly efficient, typically operating in O(1) (constant time) on average, because it leverages the hash table's underlying structure to quickly locate the key's potential bucket. In the worst-case scenario (due to hash collisions), it can degrade to O(n). Using `containsKey()` is often preferred over checking if `get(key)` returns `null` when you only need to know about the key's existence, as `get()` might legitimately return `null` if a key is present but its associated value is `null`. This method is crucial for conditional logic, preventing `NullPointerException` when retrieving values, or ensuring uniqueness of keys before insertion. It can also handle `null` keys correctly if the map supports them.

Quick reference

Syntax

boolean HashMap.containsKey(Object key)

Inputs

Parameters

keyObject · The key whose presence in this map is to be tested.

See it in practice

Examples

1

Checking for key existence

import java.util.HashMap;

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 100);
scores.put("Bob", 95);

System.out.println("Contains 'Alice': " + scores.containsKey("Alice"));
System.out.println("Contains 'Charlie': " + scores.containsKey("Charlie"));
Output:
Contains 'Alice': true Contains 'Charlie': false

Demonstrates how `containsKey()` returns `true` for an existing key and `false` for a non-existent key.

2

Distinguishing between non-existent key and null value

import java.util.HashMap;

HashMap<String, String> config = new HashMap<>();
config.put("theme", "dark");
config.put("language", null);

System.out.println("Contains 'theme': " + config.containsKey("theme"));
System.out.println("Value of 'theme': " + config.get("theme"));

System.out.println("Contains 'language': " + config.containsKey("language"));
System.out.println("Value of 'language': " + config.get("language"));

System.out.println("Contains 'font': " + config.containsKey("font"));
System.out.println("Value of 'font': " + config.get("font"));
Output:
Contains 'theme': true Value of 'theme': dark Contains 'language': true Value of 'language': null Contains 'font': false Value of 'font': null

Highlights the importance of `containsKey()`: `get()` returns `null` for both non-existent keys and keys with `null` values. `containsKey()` correctly differentiates these cases.

3

Conditional insertion using containsKey

import java.util.HashMap;

HashMap<String, String> userRoles = new HashMap<>();
userRoles.put("admin", "Administrator");

String newUser = "guest";
if (!userRoles.containsKey(newUser)) {
    userRoles.put(newUser, "Guest User");
    System.out.println("Added new user: " + newUser);
} else {
    System.out.println("User " + newUser + " already exists.");
}

String existingUser = "admin";
if (!userRoles.containsKey(existingUser)) {
    userRoles.put(existingUser, "Super Admin");
} else {
    System.out.println("User " + existingUser + " already exists.");
}
System.out.println(userRoles);
Output:
Added new user: guest User admin already exists. {guest=Guest User, admin=Administrator}

Shows how `containsKey()` can be used to prevent overwriting existing entries or to perform actions only if a key is not present.

Debug faster

Common Errors

1

Relying on `get(key) == null` for key existence

Cause: If a `HashMap` can legitimately store `null` values, then `map.get(key) == null` does not definitively tell you if the key is absent or if it maps to a `null` value. This can lead to incorrect logic.

Fix: Always use `map.containsKey(key)` to check for the presence of a key. If the key exists, then `map.get(key)` can be used to retrieve its value, which might be `null`.

import java.util.HashMap;

HashMap<String, String> config = new HashMap<>();
config.put("setting1", null);

// Incorrect: This will print 'Key not found' even though setting1 exists
if (config.get("setting1") == null) {
    System.out.println("Key 'setting1' not found or has null value.");
}

// Correct:
if (config.containsKey("setting1")) {
    System.out.println("Key 'setting1' exists. Value: " + config.get("setting1"));
} else {
    System.out.println("Key 'setting1' does not exist.");
}

Runtime support

Compatibility

JVMN/AJava 1.2+

Source: Oracle Java Documentation

Common questions

Frequently Asked Questions

Checks if the HashMap contains a mapping for the specified key.

key: The key whose presence in this map is to be tested.

Relying on `get(key) == null` for key existence: Always use `map.containsKey(key)` to check for the presence of a key. If the key exists, then `map.get(key)` can be used to retrieve its value, which might be `null`.