How to check if a map contains a key
Short answer
containsKey() checks whether a key is present:
void main() {
var stock = Map.of("tea", 5, "cake", 0);
IO.println(stock.containsKey("tea"));
IO.println(stock.containsKey("coffee"));
}Output:
true
falseA value
containsValue() searches the values. It scans the whole Map, so it is slower:
void main() {
var stock = Map.of("tea", 5, "cake", 0);
IO.println(stock.containsValue(0));
}Output:
trueChecking and getting at once
If you need the value anyway, get it and check for null — that is one lookup instead of two:
void main() {
var emails = Map.of("anna", "anna@site.com");
String email = emails.get("anna");
if (email != null) {
IO.println("Send to " + email);
}
}Output:
Send to anna@site.comCommon mistake
Checking for a key with get() != null when null can be a value. HashMap allows null, and a key with such a value looks missing:
void main() {
var phones = new HashMap<String, String>();
phones.put("oleg", null);
IO.println(phones.get("oleg") != null);
IO.println(phones.containsKey("oleg"));
}Output:
false
trueFunctions used in this recipe
- Map.containsKey() — Checks whether a map has a key.
- Map.get() — Returns the value for a key, or `null`.