Start learning free

LESSON 127 OF 671 · DICTIONARIES

Reading a Key That May Be Missing in Java

Lesson

TL ; DR:

map.getOrDefault(key, 0) gives the key's value, or 0 when the key is missing.


HashMap<String, Integer> points = new HashMap<>();
points.put("Ana", 7);

System.out.println(points.getOrDefault("Ana", 0));   // 7
System.out.println(points.getOrDefault("Ben", 0));   // 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

points.get("Ben") gives null. Storing that null in an int crashes the program with a NullPointerException.

getOrDefault takes a key and a default. It gives the key's value when the key is there. It gives the default when it isn't.

Reading this way doesn't add the key. points still has one key afterwards.

It does what this if with containsKey does, in one line:

int score = 0;
if (points.containsKey("Ben")) {
    score = points.get("Ben");
}

Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Read "plums" with getOrDefault and 0 as the default. Store it in an int named plums.

Then print the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 2
    Ctrl + Enter to check