Java 25 (LTS) reference · Map and HashMap Methods

Java Map containsKey() Method

Return true if the map has an entry for the key, even when its value is null. O(1) for HashMap.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.containsKey(key)

Parameters

ParameterDescription
key
Object
The key to check.

Return value

true or false.

Examples

containsKey() vs get() != null
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, String> settings = new HashMap<>();
        settings.put("theme", null);
        System.out.println(settings.containsKey("theme"));
        System.out.println(settings.get("theme") != null);
    }
}

Output

true
false

Run this on your computer — see “Get Started” for setup.

Username checks
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> users = Map.of("ana", 1);
        System.out.println(users.containsKey("ana") ? "taken" : "available");
        System.out.println(users.containsValue(1));
    }
}

Output

taken
true

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?