Map.containsKey()
Checks whether a map has a key.
Available since: Java 1.2
Syntax
boolean containsKey(Object key)
boolean containsValue(Object value)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | Object | The key to check. |
Return value
boolean`true` if the key exists.
Examples
Keys and values:
void main() {
Map<String, Integer> rooms = Map.of("A101", 30, "B202", 12);
IO.println(rooms.containsKey("A101"));
IO.println(rooms.containsKey("C303"));
IO.println(rooms.containsValue(12));
}Output:
true
false
trueNotes
containsKey() is fast, while containsValue() scans all values. If you call get() right after the check, it is simpler to call only get() and compare with null, or use getOrDefault().
See also
- Map.get() — Returns the value for a key, or `null`.
- Set.contains() — Checks whether a set contains an element.
- Map.getOrDefault() — Returns the value for a key, or a fallback when the key is absent.
Related recipes
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.