Start learning free

LESSON 99 OF 344 · DICTIONARIES

Accessing Dictionary Values in Java: HashMap get and getOrDefault

Lesson Read the full explanation

In Java, you access values in a HashMap using the get(key) method:

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);

int aliceScore = scores.get("Alice");  // 95
int bobScore = scores.get("Bob");      // 87

If the key doesn't exist, get() returns null. Use getOrDefault() to provide a fallback:

int score = scores.getOrDefault("Diana", 0);  // returns 0 if not found

Check if a key exists with containsKey():

if (scores.containsKey("Alice")) {
    System.out.println(scores.get("Alice"));
}

Assignment
Follow the Coding Tutorial and access Alice's score from scores!


Hint
Use scores.get("Alice") and assign it to aliceScore.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · DICTIONARIES

    Accessing Dictionary Values in Java, explained

    Reading a value by its key

    To read a value out of a HashMap, call get with the key. The map finds the entry for that key and returns its value:

    HashMap<String, Integer> scores = new HashMap<>();
    scores.put("Alice", 95);
    scores.put("Bob", 87);
    
    int aliceScore = scores.get("Alice");   // 95
    int bobScore = scores.get("Bob");       // 87
    

    Notice that you ask by key, not by position. A map has no index like an array's [0], and reading a value doesn't remove it from the map.

    What happens when the key is missing

    If the map has no entry for the key, get returns null. It does not throw an exception:

    System.out.println(scores.get("Diana"));   // null
    

    This leads to the most common mistake with maps. The return type of get is Integer, the object wrapper, and not int. Assigning it to an int variable makes Java unwrap the number automatically, and unwrapping null fails:

    int missing = scores.get("Diana");   // throws NullPointerException
    

    The line compiles fine, and the program crashes when it runs. There are two ways to handle a missing key safely.

    Provide a fallback with getOrDefault

    int score = scores.getOrDefault("Diana", 0);   // 0 if not found
    

    getOrDefault(key, fallback) returns the stored value when the key exists and the fallback otherwise. The map itself is not changed; no Diana entry is added. This is the tool for counting loops: counts.put(w, counts.getOrDefault(w, 0) + 1) adds one to a word's count, starting from zero the first time.

    Check first with containsKey

    if (scores.containsKey("Alice")) {
        System.out.println(scores.get("Alice"));
    }
    

    containsKey(key) returns a boolean. It is the right choice when a missing key needs different handling, not just a default number. A related method, containsValue(value), looks for a value instead, and it has to scan the entries to do so.

    Reading many values

    Sometimes you don't know the keys in advance and want to go through everything in the map. Three views are available:

    • keySet() gives all the keys, and you can call get on each one.
    • values() gives just the values.
    • entrySet() gives key-value pairs together, each with getKey() and getValue().
    HashMap<String, Integer> s = new HashMap<>();
    s.put("Alice", 95);
    s.put("Bob", 87);
    
    int total = 0;
    for (int v : s.values()) {
        total += v;
    }
    System.out.println(total);   // 182
    

    The order in which these views list the entries is not specified for a HashMap, so write code that gives the right answer in any order, as the sum does. To count items with getOrDefault, the pattern looks like this:

    HashMap<String, Integer> counts = new HashMap<>();
    for (String w : "a b a c a".split(" ")) {
        counts.put(w, counts.getOrDefault(w, 0) + 1);
    }
    System.out.println(counts.get("a"));   // 3
    System.out.println(counts.get("z"));   // null
    

    Each word is looked up with a fallback of 0, incremented, and stored back with put. A word that never appeared, such as "z", still gives null from get.

    The lesson's exercise

    The starting code builds a map of three scores:

    HashMap<String, Integer> scores = new HashMap<>();
    scores.put("Alice", 95);
    scores.put("Bob", 87);
    scores.put("Charlie", 72);
    

    The task has one step: read Alice's score. Declare an int named aliceScore below the map and assign it scores.get("Alice"). The key "Alice" exists, so there is no null to worry about, and the value 95 is unwrapped into the int.

    Declaring the variable as int is fine here only because the key is known to be present. If the key could be absent, you would use getOrDefault, or declare the variable as Integer and test it for null before using it as a number.

    The complete code is:

    HashMap<String, Integer> scores = new HashMap<>();
    scores.put("Alice", 95);
    scores.put("Bob", 87);
    scores.put("Charlie", 72);
    
    int aliceScore = scores.get("Alice");
    

    Gotchas

    • Keys are case-sensitive. scores.get("alice") returns null here, because the stored key is "Alice".
    • A null result is ambiguous. A HashMap allows null values, so get returning null can mean either "no such key" or "the key maps to null". Use containsKey to tell them apart.
    • Use Integer to keep the null. Writing Integer maybe = scores.get("Diana"); stores null without crashing, and you can test it with maybe == null.
    • The key type must match. On a map with String keys, get(5) compiles but always returns null, because an integer is never equal to a string key.
    • Getting does not modify. Neither get nor getOrDefault adds a missing key.

    Key takeaways

    • map.get(key) returns the value for the key, or null if the key is absent.
    • Assigning that null to an int throws a NullPointerException.
    • getOrDefault(key, fallback) gives a safe default, and containsKey(key) tests for presence.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free