Start learning free

LESSON 122 OF 671 · DICTIONARIES

Dictionaries (HashMap) in Java

Lesson

In Java, a HashMap works like a dictionary — it stores key-value pairs where each key maps to a value. You need to import java.util.HashMap.

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

The type parameters <String, Integer> specify the key type and value type. Use put(key, value) to add entries:

HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
System.out.println(ages.get("Alice"));  // 25
System.out.println(ages.size());        // 2

Assignment
Follow the Coding Tutorial and create a HashMap named scores with three student scores!


Hint
Declare HashMap<String, Integer> scores = new HashMap<>() then use put() to add entries.

STEP 1 OF 2
    Ctrl + Enter to check