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
Syntax
map.containsKey(key)
Parameters
| Parameter | Description |
|---|---|
keyObject |
The key to check. |
Return value
true or false.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
map.get()· Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls.list.contains()· Return true if the list holds an element equal to the given one (using equals()). O(n) for ArrayList.- Java HashMap · tutorial