Start learning free

LESSON 126 OF 671 · DICTIONARIES

Checking for a Key in Java

Lesson

TL ; DR:

Call map.containsKey(key) to ask whether a HashMap has a key. It returns true or false, so it goes in an if.


HashMap<String, String> capitals = new HashMap<>();
capitals.put("France", "Paris");
capitals.put("Japan", "Tokyo");

if (capitals.containsKey("Japan")) {
    System.out.println(capitals.get("Japan"));   // Tokyo
}

if (!capitals.containsKey("Spain")) {
    System.out.println("No Spain");              // No Spain
}


Full lesson:

get on a missing key gives null. Using that null later crashes the program with a NullPointerException.

So check first. capitals.containsKey("Spain") is true when "Spain" is a key. It is false when it isn't.

Put ! in front for the opposite. !capitals.containsKey("Spain") is true here.

A value is not a key

containsKey looks only at the keys. capitals.containsKey("Paris") is false, because "Paris" is a value.

To look in the values, call containsValue("Paris").

A key must match exactly, upper and lower case too. capitals.containsKey("japan") is false.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, print Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with ! and containsKey. If so, print cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check