Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.containsKey()

Checks whether a map has a key.

Available since: Java 1.2

Syntax

boolean containsKey(Object key)
boolean containsValue(Object value)

Parameters

ParameterTypeDescription
keyObjectThe 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
true

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.