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 callgeton each one.values()gives just the values.entrySet()gives key-value pairs together, each withgetKey()andgetValue().
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")returnsnullhere, because the stored key is"Alice". - A
nullresult is ambiguous. AHashMapallowsnullvalues, sogetreturningnullcan mean either "no such key" or "the key maps tonull". UsecontainsKeyto tell them apart. - Use
Integerto keep thenull. WritingInteger maybe = scores.get("Diana");storesnullwithout crashing, and you can test it withmaybe == null. - The key type must match. On a map with
Stringkeys,get(5)compiles but always returnsnull, because an integer is never equal to a string key. - Getting does not modify. Neither
getnorgetOrDefaultadds a missing key.
Key takeaways
map.get(key)returns the value for the key, ornullif the key is absent.- Assigning that
nullto anintthrows aNullPointerException. getOrDefault(key, fallback)gives a safe default, andcontainsKey(key)tests for presence.