Skip to content

HashMaps – Storing Key‐Value Pairs

Seanti edited this page Mar 24, 2025 · 1 revision

➡️ Think of a HashMap as a dictionary where each word (key) has a definition (value).
➡️ Instead of just storing a list of items like an ArrayList, a HashMap lets us connect two pieces of data (a key and a value).


1. Why Use a HashMap?

Feature ArrayList HashMap (✅ More Organized)
Stores multiple values? ✅ Yes ✅ Yes
Uses an index (number) to find values? ✅ Yes (0, 1, 2...) ❌ No (Uses keys instead)
Uses meaningful keys? ❌ No ✅ Yes (Can use words, names, etc.)
Fast lookup? ❌ No (Loops through everything) ✅ Yes (Directly finds the value)

Example:

Imagine you have a box of labeled gumballs.

  • With an ArrayList, you just store gumballs in order: [Red, Blue, Green].

  • With a HashMap, each gumball has a label (key), so you can find it easily:

    "A1" → Red  
    "B2" → Blue  
    "C3" → Green  
    

    Instead of searching for a color in a list, you can just look up the label!


2. Creating a HashMap

To use a HashMap, we need to import it first.

import java.util.HashMap; // Import HashMap

public class GumballMachine {
    public static void main(String[] args) {
        HashMap<String, String> gumballs = new HashMap<>(); // Create a HashMap

        gumballs.put("A1", "Red");    // Add items
        gumballs.put("B2", "Blue");
        gumballs.put("C3", "Green");

        System.out.println(gumballs); // Print all gumballs
    }
}

Output:

{A1=Red, B2=Blue, C3=Green}

🔹 .put("A1", "Red") → Adds "Red" with the key "A1".
🔹 .put("B2", "Blue") → Adds "Blue" with the key "B2".

➡️ Unlike an ArrayList, we don’t use index numbers. We use meaningful keys instead!


3. Accessing Items in a HashMap

Instead of using .get(index), we use .get(key) to find a value using its key.

System.out.println(gumballs.get("A1")); // Get the gumball at A1

Example:

public class GumballMachine {
    public static void main(String[] args) {
        HashMap<String, String> gumballs = new HashMap<>();
        gumballs.put("A1", "Red");
        gumballs.put("B2", "Blue");
        gumballs.put("C3", "Green");

        System.out.println("Gumball at A1: " + gumballs.get("A1"));
        System.out.println("Gumball at B2: " + gumballs.get("B2"));
    }
}

Output:

Gumball at A1: Red
Gumball at B2: Blue

🔹 .get("A1") → Finds the value for "A1" ("Red").
🔹 .get("B2") → Finds the value for "B2" ("Blue").

➡️ Unlike an ArrayList, we don’t need to remember index numbers!


4. Changing an Item

We can update a value using .put(key, newValue).

gumballs.put("A1", "Purple"); // Change "Red" to "Purple"

Example:

public class GumballMachine {
    public static void main(String[] args) {
        HashMap<String, String> gumballs = new HashMap<>();
        gumballs.put("A1", "Red");
        gumballs.put("B2", "Blue");
        gumballs.put("C3", "Green");

        gumballs.put("A1", "Purple"); // Change "Red" to "Purple"

        System.out.println(gumballs);
    }
}

Output:

{A1=Purple, B2=Blue, C3=Green}

🔹 "Red" at key "A1" is now "Purple".


5. Removing Items

We can remove items using .remove(key).

gumballs.remove("A1"); // Removes "A1"

Example:

public class GumballMachine {
    public static void main(String[] args) {
        HashMap<String, String> gumballs = new HashMap<>();
        gumballs.put("A1", "Red");
        gumballs.put("B2", "Blue");
        gumballs.put("C3", "Green");

        gumballs.remove("A1"); // Removes "Red"

        System.out.println(gumballs);
    }
}

Output:

{B2=Blue, C3=Green}

🔹 The key "A1" and its value "Red" are removed.


6. Checking if a Key Exists

We can check if a key exists using .containsKey(key).

if (gumballs.containsKey("A1")) {
    System.out.println("A1 exists!");
}

Example:

public class GumballMachine {
    public static void main(String[] args) {
        HashMap<String, String> gumballs = new HashMap<>();
        gumballs.put("A1", "Red");
        gumballs.put("B2", "Blue");

        if (gumballs.containsKey("A1")) {
            System.out.println("A1 exists!");
        }
    }
}

Output:

A1 exists!

🔹 .containsKey("A1") checks if "A1" exists.


7. Looping Through a HashMap

We can loop through all keys and values using a for loop.

for (String key : gumballs.keySet()) {
    System.out.println(key + " → " + gumballs.get(key));
}

Example:

public class GumballMachine {
    public static void main(String[] args) {
        HashMap<String, String> gumballs = new HashMap<>();
        gumballs.put("A1", "Red");
        gumballs.put("B2", "Blue");
        gumballs.put("C3", "Green");

        for (String key : gumballs.keySet()) {
            System.out.println(key + " → " + gumballs.get(key));
        }
    }
}

Output:

A1 → Red
B2 → Blue
C3 → Green

🔹 .keySet() gets all keys in the HashMap.
🔹 .get(key) gets each value.


8. Summary of HashMaps

Feature What It Does Example
Create a HashMap Makes a key-value map HashMap<String, String> map = new HashMap<>();
Add Items Adds key-value pairs .put("Key", "Value")
Get Items Finds a value using a key .get("Key")
Change Items Updates a value .put("Key", "New Value")
Remove Items Deletes a key-value pair .remove("Key")
Check if Key Exists Checks if a key is in the map .containsKey("Key")
Loop Through Keys Goes through all keys for (String key : map.keySet())

9. What’s Next?

Now that we can store key-value pairs using HashMaps, we’ll move on to Object-Oriented Programming (OOP) to create real-world objects in Java! 🚀

Clone this wiki locally