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.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
