Start learning free

LESSON 131 OF 671 · DICTIONARIES - CHALLENGES

Safe Lookup in Java: HashMap getOrDefault

Practice Read the full explanation

Given a HashMap scores from names to scores and a name, return the score of name, or 0 when name isn't a key of scores.

Some names you look up aren't in the dictionary at all. They have no score, so the answer for them is 0.

 

Example 1:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Ben"
Output: 75
Explanation: "Ben" is a key of scores, and its value is 75.

Example 2:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Dan"
Output: 0
Explanation: "Dan" isn't a key of scores, so the answer is 0.

Example 3:

Input: scores = {}, name = "Ana"
Output: 0
Explanation: An empty dictionary has no keys at all.

 

Constraints:

  • scores can be empty.
  • Names are single words made of English letters, and the names in scores are all different.
  • name matches a key only when it is spelled exactly the same, upper and lower case included: "ana" is not "Ana".
  • Every score is between 0 and 100.
STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · DICTIONARIES - CHALLENGES

    Safe Lookup in Java, explained

    Problem overview

    The method safeLookup receives scores, a HashMap<String, Integer> from names to scores, and a name. It returns that name's score, or 0 when the name isn't a key of the map.

    With {"Ana": 90, "Ben": 75, "Cara": 88}, "Ben" gives 75 and "Dan" gives 0. An empty map has no keys, so any name gives 0. Names must match exactly: "ana" is not "Ana".

    Approach: give the lookup a fallback

    A plain get returns null for a missing key. The method returns an int, and Java can't turn null into an int, so the program would fail on exactly the names this lesson cares about. The fix is to say what to use when the key is missing, and getOrDefault does that in one call.

    Step by step

    1. Read the score with getOrDefault(name, 0) and return it. The first argument is the key. The second is the value to hand back when the key is absent.

    The solution in Java

    class Solution {
        public int safeLookup(HashMap<String, Integer> scores, String name) {
            return scores.getOrDefault(name, 0);
        }
    }
    

    What to know about this one line:

    • The default is not stored. getOrDefault only reads. A missing name is still missing from the map afterwards.
    • The default has the value type. The map holds Integer values, so the fallback is the number 0, which Java boxes to an Integer and then unboxes to the int the method returns.
    • What goes wrong with get. int x = scores.get("Dan"); compiles, but at run time it throws a NullPointerException, because Java tries to unbox null. Assigned to an Integer variable, the same call just gives null.
    • A stored 0 and a missing key look the same. Here that is intended. When the difference matters, use containsKey.

    Another way: check with containsKey

    The same result can come from asking first and reading second, with an if on scores.containsKey(name) that returns scores.get(name) or 0. It is longer and does two lookups, so getOrDefault is the better tool for a simple fallback. Use containsKey when the missing case needs its own handling, for example to tell a stored 0 from an absent name. With {"Ben": 75, "Zero": 0}, getOrDefault("Zero", -1) gives 0 and getOrDefault("Dan", -1) gives -1, so a different default can tell the two cases apart, while containsKey("Dan") is false in any case.

    Why the default is 0 here

    The default is part of the task, not of getOrDefault: the statement says an unknown name has no score, so its answer is 0. The same method can fall back to anything that fits the value type, such as an empty string for a HashMap<String, String>. The map is never changed, so calling safeLookup twice with the same arguments always gives the same answer.

    Edge cases and common mistakes

    • Case. Keys are compared with equals, so "ana" gives 0 when only "Ana" is stored.
    • Empty map. getOrDefault on an empty map returns the default, so no special case is needed.
    • Checking the result for null. A condition like scores.get(name) == null works for a missing key, but getOrDefault is shorter.
    • Wrong default. Passing -1 or leaving out the second argument won't give the 0 the task asks for.

    Testing

    • The map above with "Ben" gives 75.
    • The map above with "Dan" gives 0.
    • An empty map with "Ana" gives 0.
    • The map above with "ana" gives 0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free