Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
false

A 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:

true

Checking 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.com

Common 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
true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.