You're building a phone book. Given a name, you need the phone number instantly. Arrays require searching through every entry. HashMap gives you direct lookup by key - O(1) instead of O(n).

Create a phone book

Store name-to-number associations.

PhoneBook.java
Replay: real traced execution (multi-file project)
import java.util.HashMap;

public class PhoneBook {
    public static void main(String[] args) {
        // Create a phone book
        HashMap<String, String> phoneBook = new HashMap<>();

        System.out.println("=== Building Phone Book ===");

        // Add contacts
        phoneBook.put("Alice", "555-1234");
        System.out.println("Added Alice: " + phoneBook);

        phoneBook.put("Bob", "555-5678");
        System.out.println("Added Bob: " + phoneBook);

        phoneBook.put("Carol", "555-9999");
        System.out.println("Added Carol: " + phoneBook);

        // Add more contacts
        phoneBook.put("David", "555-1111");
        phoneBook.put("Eve", "555-2222");
        phoneBook.put("Frank", "555-3333");
        System.out.println("\nWith more contacts: " + phoneBook);

        System.out.println("\n=== Phone Book Contents ===");
        System.out.println("Total contacts: " + phoneBook.size());

        // Look up a number
        String name = "Bob";
        String number = phoneBook.get(name);
        System.out.println("\n" + name + "'s number: " + number);

        // Display all contacts nicely
        System.out.println("\n=== All Contacts ===");
        for (String key : phoneBook.keySet()) {
            System.out.println(key + ": " + phoneBook.get(key));
        }
    }
}
  1. phoneBook ← {}, name ← Bob, number ← 555-5678

    4public class PhoneBook {5    public static void main(String[] args) {6        // Create a phone book  //#?create7        HashMap<String, String> phoneBook→ {} = new HashMap<>();8        9        System.out.println("=== Building Phone Book ===");10        11        // Add contacts  //#?put12        phoneBook.put("Alice", "555-1234");13        System.out.println("Added Alice: " + phoneBook{Alice=555-1234});14        15        phoneBook.put("Bob", "555-5678");16        System.out.println("Added Bob: " + phoneBook{Bob=555-5678, Alice=555-1234});17        18        phoneBook.put("Carol", "555-9999");19        System.out.println("Added Carol: " + phoneBook{Bob=555-5678, Alice=555-1234, Carol=555-9999});20        21        // Add more contacts22        phoneBook.put("David", "555-1111");  //@var=_,!23        phoneBook.put("Eve", "555-2222");    //@var=_,!24        phoneBook.put("Frank", "555-3333");  //@var=_,!25        System.out.println("\nWith more contacts: " + phoneBook{Bob=555-5678, Eve=555-2222, Alice=555-1234, David=555-1111, Carol=555-9999, Frank=555-3333});  //@var=_,!26        27        System.out.println("\n=== Phone Book Contents ===");28        System.out.println("Total contacts: " + phoneBook.size());29        30        // Look up a number31        String name→ Bob = "Bob";32        String number→ 555-5678 = phoneBook.get(nameBob);  //#?get33        System.out.println("\n" + nameBob + "'s number: " + number555-5678);34        35        // Display all contacts nicely36        System.out.println("\n=== All Contacts ===");37        for (String key : phoneBook.keySet()) {
    output=== Building Phone Book ===
    Added Alice: {Alice=555-1234}
    Added Bob: {Bob=555-5678, Alice=555-1234}
    Added Carol: {Bob=555-5678, Alice=555-1234, Carol=555-9999}
    
    With more contacts: {Bob=555-5678, Eve=555-2222, Alice=555-1234, David=555-1111, Carol=555-9999, Frank=555-3333}
    
    === Phone Book Contents ===
    Total contacts: 6
    
    Bob's number: 555-5678
    
    === All Contacts ===
  2. for (String key : phoneBook.keySet())

    pass 1 of 6
    36System.out.println("\n=== All Contacts ===");37for (String keyBob : phoneBook.keySet()) {38    System.out.println(keyBob + ": " + phoneBook.get(key));39}
    outputBob: 555-5678
    All 6 passes — pass 1 is the card above
    passkey
    1Bob
    2Eve
    3Alice
    4David
    5Carol
    6Frank

HashMap<String, String> maps string keys to string values. Use put() to add.

HashMap Key-value pairs with O(1) lookup. Keys must be unique.

Look up a contact

Retrieve a value by its key.

item
Lookup.java
Replay: real traced execution (multi-file project)
import java.util.HashMap;

public class Lookup {
    public static void main(String[] args) {
        HashMap<String, Integer> inventory = new HashMap<>();
        inventory.put("Apples", 50);
        inventory.put("Bananas", 30);
        inventory.put("Oranges", 25);
        inventory.put("Grapes", 40);

        System.out.println("=== Store Inventory ===");
        System.out.println(inventory);

        // Look up existing item
        String item = "Bananas";
        Integer stock = inventory.get(item);

        System.out.println("\n=== Inventory Lookup ===");
        System.out.println("Looking for: " + item);

        if (stock != null) {
            System.out.println("In stock: " + stock + " units");

            if (stock < 35) {
                System.out.println("⚠️ Low stock - consider reordering!");
            }
        } else {
            System.out.println("❌ Item not found in inventory!");
            System.out.println("Available items: " + inventory.keySet());
        }

        // Using getOrDefault
        System.out.println("\n=== Using getOrDefault ===");
        String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};

        for (String checkItem : checkItems) {
            int qty = inventory.getOrDefault(checkItem, 0);
            String status = qty > 0 ? "✓ " + qty + " in stock" : "✗ Not available";
            System.out.println(checkItem + ": " + status);
        }
    }
}
import java.util.HashMap;

public class Lookup {
    public static void main(String[] args) {
        HashMap<String, Integer> inventory = new HashMap<>();
        inventory.put("Apples", 50);
        inventory.put("Bananas", 30);
        inventory.put("Oranges", 25);
        inventory.put("Grapes", 40);

        System.out.println("=== Store Inventory ===");
        System.out.println(inventory);

        // Look up existing item
        String item = "Mangoes";
        Integer stock = inventory.get(item);

        System.out.println("\n=== Inventory Lookup ===");
        System.out.println("Looking for: " + item);

        if (stock != null) {
            System.out.println("In stock: " + stock + " units");

            if (stock < 35) {
                System.out.println("⚠️ Low stock - consider reordering!");
            }
        } else {
            System.out.println("❌ Item not found in inventory!");
            System.out.println("Available items: " + inventory.keySet());
        }

        // Using getOrDefault
        System.out.println("\n=== Using getOrDefault ===");
        String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};

        for (String checkItem : checkItems) {
            int qty = inventory.getOrDefault(checkItem, 0);
            String status = qty > 0 ? "✓ " + qty + " in stock" : "✗ Not available";
            System.out.println(checkItem + ": " + status);
        }
    }
}
  1. inventory ← {}, item ← Bananas, stock ← 30

    4public class Lookup {5    public static void main(String[] args) {6        HashMap<String, Integer> inventory→ {} = new HashMap<>();7        inventory.put("Apples", 50);8        inventory.put("Bananas", 30);9        inventory.put("Oranges", 25);10        inventory.put("Grapes", 40);11        12        System.out.println("=== Store Inventory ===");13        System.out.println(inventory{Apples=50, Bananas=30, Grapes=40, Oranges=25});14        15        // Look up existing item  //#?lookup16        String item→ Bananas = "Bananas";  //@var=_,Mangoes17        Integer stock→ 30 = inventory.get(itemBananas);18        19        System.out.println("\n=== Inventory Lookup ===");20        System.out.println("Looking for: " + itemBananas);
    output=== Store Inventory ===
    {Apples=50, Bananas=30, Grapes=40, Oranges=25}
    
    === Inventory Lookup ===
    Looking for: Bananas
  2. if (stock != null)

    22if (stock30 != null) {  //#?nullcheck23    System.out.println("In stock: " + stock30 + " units");
    outputIn stock: 30 units
  3. if (stock < 35)

    25if (stock30 < 35) {26    System.out.println("⚠️ Low stock - consider reordering!");27}
    output⚠️ Low stock - consider reordering!
  4. String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};

    33// Using getOrDefault  //#?default34System.out.println("\n=== Using getOrDefault ===");35String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};
    output
    === Using getOrDefault ===
  5. qty ← 50, status ← ✓ 50 in stock

    pass 1 of 4
    37for (String checkItemApples : checkItems) {38    int qty→ 50 = inventory.getOrDefault(checkItemApples, 0);39    String status→ ✓ 50 in stock = qty50 > 0 ? "✓ " + qty + " in stock" : "✗ Not available";40    System.out.println(checkItemApples + ": " + status✓ 50 in stock);41}
    outputApples: ✓ 50 in stock
    All 4 passes — pass 1 is the card above
    passcheckItemqtystatus
    1Apples50✓ 50 in stock
    2Mangoes0✗ Not available
    3Oranges25✓ 25 in stock
    4Pears0✗ Not available
  1. inventory ← {}, item ← Mangoes, stock ← null

    3public class Lookup {4    public static void main(String[] args) {5        HashMap<String, Integer> inventory→ {} = new HashMap<>();6        inventory.put("Apples", 50);7        inventory.put("Bananas", 30);8        inventory.put("Oranges", 25);9        inventory.put("Grapes", 40);10        11        System.out.println("=== Store Inventory ===");12        System.out.println(inventory{Apples=50, Bananas=30, Grapes=40, Oranges=25});13        14        // Look up existing item15        String item→ Mangoes = "Mangoes";16        Integer stock→ null = inventory.get(itemMangoes);17        18        System.out.println("\n=== Inventory Lookup ===");19        System.out.println("Looking for: " + itemMangoes);
    output=== Store Inventory ===
    {Apples=50, Bananas=30, Grapes=40, Oranges=25}
    
    === Inventory Lookup ===
    Looking for: Mangoes
  2. else

    26    }27} else {28    System.out.println("❌ Item not found in inventory!");29    System.out.println("Available items: " + inventory.keySet());30}
    output❌ Item not found in inventory!
    Available items: [Apples, Bananas, Grapes, Oranges]
  3. String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};

    32// Using getOrDefault33System.out.println("\n=== Using getOrDefault ===");34String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};
    output
    === Using getOrDefault ===
  4. qty ← 50, status ← ✓ 50 in stock

    pass 1 of 4
    36for (String checkItemApples : checkItems) {37    int qty→ 50 = inventory.getOrDefault(checkItemApples, 0);38    String status→ ✓ 50 in stock = qty50 > 0 ? "✓ " + qty + " in stock" : "✗ Not available";39    System.out.println(checkItemApples + ": " + status✓ 50 in stock);40}
    outputApples: ✓ 50 in stock
    All 4 passes — pass 1 is the card above
    passcheckItemqtystatus
    1Apples50✓ 50 in stock
    2Mangoes0✗ Not available
    3Oranges25✓ 25 in stock
    4Pears0✗ Not available

get(key) returns the value, or null if key doesn't exist.

Update an entry

Change the value associated with a key.

UpdateEntry.java
Replay: real traced execution (multi-file project)
import java.util.HashMap;

public class UpdateEntry {
    public static void main(String[] args) {
        HashMap<String, Integer> inventory = new HashMap<>();
        inventory.put("Apples", 50);
        inventory.put("Bananas", 30);
        inventory.put("Oranges", 25);

        System.out.println("=== Initial Inventory ===");
        System.out.println(inventory);

        // Update: Restock apples
        String item = "Apples";
        int addAmount = 20;

        int oldStock = inventory.get(item);
        int newStock = oldStock + addAmount;
        inventory.put(item, newStock);  // put() overwrites

        System.out.println("\n=== After Restocking ===");
        System.out.println(item + ": " + oldStock + " → " + newStock);
        System.out.println(inventory);

        // Sell some items (decrease)
        item = "Bananas";
        int sold = 5;
        inventory.put(item, inventory.get(item) - sold);
        System.out.println("\nSold " + sold + " " + item);
        System.out.println(inventory);

        // Word frequency counter
        System.out.println("\n=== Word Frequency Counter ===");
        String text = "apple banana apple orange apple banana grape";
        String[] words = text.split(" ");

        HashMap<String, Integer> wordCount = new HashMap<>();

        for (String word : words) {
            // Get current count (0 if not seen), add 1
            int count = wordCount.getOrDefault(word, 0);
            wordCount.put(word, count + 1);
        }

        System.out.println("Text: \"" + text + "\"");
        System.out.println("Word counts: " + wordCount);
    }
}
  1. inventory ← {}, item ← Apples, addAmount ← 20, oldStock ← 50, newStock ← 70

    4public class UpdateEntry {5    public static void main(String[] args) {6        HashMap<String, Integer> inventory→ {} = new HashMap<>();7        inventory.put("Apples", 50);8        inventory.put("Bananas", 30);9        inventory.put("Oranges", 25);10        11        System.out.println("=== Initial Inventory ===");12        System.out.println(inventory{Apples=50, Bananas=30, Oranges=25});13        14        // Update: Restock apples  //#?update15        String item→ Apples = "Apples";16        int addAmount→ 20 = 20;17        18        int oldStock→ 50 = inventory.get(itemApples);19        int newStock→ 70 = oldStock50 + addAmount20;20        inventory.put(itemApples, newStock70);  // put() overwrites21        22        System.out.println("\n=== After Restocking ===");23        System.out.println(itemApples + ": " + oldStock50 + " → " + newStock70);24        System.out.println(inventory{Apples=70, Bananas=30, Oranges=25});25        26        // Sell some items (decrease)27        item→ Bananas = "Bananas";28        int sold→ 5 = 5;29        inventory.put(itemBananas, inventory.get(item) - sold5);  //@var=_,!30        System.out.println("\nSold " + sold5 + " " + itemBananas);  //@var=_,!31        System.out.println(inventory{Apples=70, Bananas=25, Oranges=25});  //@var=_,!32        33        // Word frequency counter  //#?freq   //@var=!,_34        System.out.println("\n=== Word Frequency Counter ===");  //@var=!,_35        String text→ apple banana apple orange apple banana grape = "apple banana apple orange apple banana grape";  //@var=!,_36        String[] words = text.split(" ");  //@var=!,_37        38        HashMap<String, Integer> wordCount→ {} = new HashMap<>();  //@var=!,_
    output=== Initial Inventory ===
    {Apples=50, Bananas=30, Oranges=25}
    
    === After Restocking ===
    Apples: 50 → 70
    {Apples=70, Bananas=30, Oranges=25}
    
    Sold 5 Bananas
    {Apples=70, Bananas=25, Oranges=25}
    
    === Word Frequency Counter ===
  2. count ← 0

    pass 1 of 7
    40for (String wordapple : words) {  //@var=!,_41    // Get current count (0 if not seen), add 1  //@var=!,_42    int count→ 0 = wordCount.getOrDefault(wordapple, 0);  //@var=!,_43    wordCount.put(wordapple, count0 + 1);  //@var=!,_44}  //@var=!,_
    All 7 passes — pass 1 is the card above
    passwordcount
    1apple0
    2banana0
    3apple1
    4orange0
    5apple2
    6banana1
    7grape0
  3. System.out.println("Text: \"" + text + "\""); //@var=!,_

    46    System.out.println("Text: \"" + textapple banana apple orange apple banana grape + "\"");  //@var=!,_47    System.out.println("Word counts: " + wordCount{banana=2, orange=1, apple=3, grape=1});  //@var=!,_48}
    outputText: "apple banana apple orange apple banana grape"
    Word counts: {banana=2, orange=1, apple=3, grape=1}

put() with existing key replaces the old value.

Check if key exists

Test whether a key is in the map before accessing.

username
CheckKey.java
Replay: real traced execution (multi-file project)
import java.util.HashMap;

public class CheckKey {
    public static void main(String[] args) {
        HashMap<String, String> userPasswords = new HashMap<>();
        userPasswords.put("alice", "pass123");
        userPasswords.put("bob", "secret456");
        userPasswords.put("carol", "hunter2");

        System.out.println("=== Login System ===");
        System.out.println("Registered users: " + userPasswords.keySet());

        // Login attempt
        String username = "bob";
        String password = "secret456";

        System.out.println("\n=== Login Attempt ===");
        System.out.println("Username: " + username);

        // Step 1: Check if user exists
        if (userPasswords.containsKey(username)) {
            System.out.println("✓ User found");

            // Step 2: Verify password
            String correctPassword = userPasswords.get(username);
            if (correctPassword.equals(password)) {
                System.out.println("✓ Password correct");
                System.out.println("🎉 Login successful!");
            } else {
                System.out.println("✗ Incorrect password");
            }
        } else {
            System.out.println("✗ User not found");
            System.out.println("Would you like to register?");
        }

        // Check both key and value
        System.out.println("\n=== Security Check ===");
        String weakPassword = "pass123";

        if (userPasswords.containsValue(weakPassword)) {
            System.out.println("⚠️ Someone is using a weak password!");
        }

        // Find which user has weak password
        for (String user : userPasswords.keySet()) {
            if (userPasswords.get(user).equals(weakPassword)) {
                System.out.println("User with weak password: " + user);
            }
        }
    }
}
import java.util.HashMap;

public class CheckKey {
    public static void main(String[] args) {
        HashMap<String, String> userPasswords = new HashMap<>();
        userPasswords.put("alice", "pass123");
        userPasswords.put("bob", "secret456");
        userPasswords.put("carol", "hunter2");

        System.out.println("=== Login System ===");
        System.out.println("Registered users: " + userPasswords.keySet());

        // Login attempt
        String username = "eve";
        String password = "secret456";

        System.out.println("\n=== Login Attempt ===");
        System.out.println("Username: " + username);

        // Step 1: Check if user exists
        if (userPasswords.containsKey(username)) {
            System.out.println("✓ User found");

            // Step 2: Verify password
            String correctPassword = userPasswords.get(username);
            if (correctPassword.equals(password)) {
                System.out.println("✓ Password correct");
                System.out.println("🎉 Login successful!");
            } else {
                System.out.println("✗ Incorrect password");
            }
        } else {
            System.out.println("✗ User not found");
            System.out.println("Would you like to register?");
        }

        // Check both key and value
        System.out.println("\n=== Security Check ===");
        String weakPassword = "pass123";

        if (userPasswords.containsValue(weakPassword)) {
            System.out.println("⚠️ Someone is using a weak password!");
        }

        // Find which user has weak password
        for (String user : userPasswords.keySet()) {
            if (userPasswords.get(user).equals(weakPassword)) {
                System.out.println("User with weak password: " + user);
            }
        }
    }
}
  1. userPasswords ← {}, username ← bob, password ← secret456

    4public class CheckKey {5    public static void main(String[] args) {6        HashMap<String, String> userPasswords→ {} = new HashMap<>();7        userPasswords.put("alice", "pass123");8        userPasswords.put("bob", "secret456");9        userPasswords.put("carol", "hunter2");10        11        System.out.println("=== Login System ===");12        System.out.println("Registered users: " + userPasswords.keySet());13        14        // Login attempt15        String username→ bob = "bob";     //@var=_,eve16        String password→ secret456 = "secret456";17        18        System.out.println("\n=== Login Attempt ===");19        System.out.println("Username: " + usernamebob);
    output=== Login System ===
    Registered users: [carol, bob, alice]
    
    === Login Attempt ===
    Username: bob
  2. correctPassword ← secret456

    21// Step 1: Check if user exists  //#?contains22if (userPasswords.containsKey(usernamebob)) {23    System.out.println("✓ User found");24    25    // Step 2: Verify password26    String correctPassword→ secret456 = userPasswords.get(usernamebob);27    if (correctPassword.equals(password)) {
    output✓ User found
  3. if (correctPassword.equals(password))

    26String correctPassword = userPasswords.get(username);27if (correctPassword.equals(passwordsecret456)) {28    System.out.println("✓ Password correct");29    System.out.println("🎉 Login successful!");30} else {
    output✓ Password correct
    🎉 Login successful!
  4. weakPassword ← pass123

    38// Check both key and value  //#?containsval39System.out.println("\n=== Security Check ===");40String weakPassword→ pass123 = "pass123";
    output
    === Security Check ===
  5. if (userPasswords.containsValue(weakPassword))

    42if (userPasswords.containsValue(weakPasswordpass123)) {43    System.out.println("⚠️ Someone is using a weak password!");44}
    output⚠️ Someone is using a weak password!
  6. for (String user : userPasswords.keySet())

    pass 1 of 3
    46// Find which user has weak password47for (String usercarol : userPasswords.keySet()) {48    if (userPasswords.get(user).equals(weakPassword)) {
    All 3 passes — pass 1 is the card above
    passuserweakPassword
    1carol
    2bob
    3alicepass123
  7. if (userPasswords.get(user).equals(weakPassword))

    47for (String user : userPasswords.keySet()) {48    if (userPasswords.get(useralice).equals(weakPasswordpass123)) {49        System.out.println("User with weak password: " + useralice);50    }
    outputUser with weak password: alice
  1. userPasswords ← {}, username ← eve, password ← secret456

    3public class CheckKey {4    public static void main(String[] args) {5        HashMap<String, String> userPasswords→ {} = new HashMap<>();6        userPasswords.put("alice", "pass123");7        userPasswords.put("bob", "secret456");8        userPasswords.put("carol", "hunter2");9        10        System.out.println("=== Login System ===");11        System.out.println("Registered users: " + userPasswords.keySet());12        13        // Login attempt14        String username→ eve = "eve";15        String password→ secret456 = "secret456";16        17        System.out.println("\n=== Login Attempt ===");18        System.out.println("Username: " + usernameeve);
    output=== Login System ===
    Registered users: [carol, bob, alice]
    
    === Login Attempt ===
    Username: eve
  2. else

    31    }32} else {33    System.out.println("✗ User not found");34    System.out.println("Would you like to register?");35}
    output✗ User not found
    Would you like to register?
  3. weakPassword ← pass123

    37// Check both key and value38System.out.println("\n=== Security Check ===");39String weakPassword→ pass123 = "pass123";
    output
    === Security Check ===
  4. if (userPasswords.containsValue(weakPassword))

    41if (userPasswords.containsValue(weakPasswordpass123)) {42    System.out.println("⚠️ Someone is using a weak password!");43}
    output⚠️ Someone is using a weak password!
  5. for (String user : userPasswords.keySet())

    pass 1 of 3
    45// Find which user has weak password46for (String usercarol : userPasswords.keySet()) {47    if (userPasswords.get(user).equals(weakPassword)) {
    All 3 passes — pass 1 is the card above
    passuserweakPassword
    1carol
    2bob
    3alicepass123
  6. if (userPasswords.get(user).equals(weakPassword))

    46for (String user : userPasswords.keySet()) {47    if (userPasswords.get(useralice).equals(weakPasswordpass123)) {48        System.out.println("User with weak password: " + useralice);49    }
    outputUser with weak password: alice

containsKey() prevents null surprises. Check before using the value.

containsKey Test key existence: `map.containsKey("key")`. Returns true/false.

Iterate through entries

Loop through all keys, values, or key-value pairs.

IterateMap.java
Replay: real traced execution (multi-file project)
import java.util.HashMap;
import java.util.Map;

public class IterateMap {
    public static void main(String[] args) {
        HashMap<String, Double> prices = new HashMap<>();
        prices.put("Coffee", 4.50);
        prices.put("Tea", 3.00);
        prices.put("Juice", 5.25);
        prices.put("Water", 1.50);
        prices.put("Soda", 2.75);

        System.out.println("=== Café Menu ===\n");

        // Method 1: Iterate keys only
        System.out.println("1. Keys only (keySet):");
        for (String item : prices.keySet()) {
            System.out.println("   • " + item);
        }

        // Method 2: Iterate values only
        System.out.println("\n2. Values only (values):");
        double total = 0;
        for (Double price : prices.values()) {
            total += price;
            System.out.printf("   $%.2f%n", price);
        }
        System.out.printf("   Total: $%.2f%n", total);

        // Method 3: Iterate both (entrySet) - MOST COMMON
        System.out.println("\n3. Keys and Values (entrySet):");
        for (Map.Entry<String, Double> entry : prices.entrySet()) {
            String item = entry.getKey();
            Double price = entry.getValue();
            System.out.printf("   %-10s $%.2f%n", item, price);
        }

        // Method 4: forEach with lambda (Java 8+)
        System.out.println("\n4. forEach lambda:");
        prices.forEach((item, price) ->
            System.out.printf("   %s → $%.2f%n", item, price)
        );

        // Find max and min priced items
        System.out.println("\n=== Price Analysis ===");
        String cheapest = null;
        String expensive = null;
        double minPrice = Double.MAX_VALUE;
        double maxPrice = Double.MIN_VALUE;

        for (Map.Entry<String, Double> entry : prices.entrySet()) {
            if (entry.getValue() < minPrice) {
                minPrice = entry.getValue();
                cheapest = entry.getKey();
            }
            if (entry.getValue() > maxPrice) {
                maxPrice = entry.getValue();
                expensive = entry.getKey();
            }
        }
        System.out.printf("Cheapest: %s ($%.2f)%n", cheapest, minPrice);
        System.out.printf("Most expensive: %s ($%.2f)%n", expensive, maxPrice);
    }
}
  1. prices ← {}

    4public class IterateMap {5    public static void main(String[] args) {6        HashMap<String, Double> prices→ {} = new HashMap<>();7        prices.put("Coffee", 4.50);8        prices.put("Tea", 3.00);9        prices.put("Juice", 5.25);10        prices.put("Water", 1.50);11        prices.put("Soda", 2.75);12        13        System.out.println("=== Café Menu ===\n");14        15        // Method 1: Iterate keys only  //#?keys16        System.out.println("1. Keys only (keySet):");17        for (String item : prices.keySet()) {
    output=== Café Menu ===
    1. Keys only (keySet):
  2. for (String item : prices.keySet())

    pass 1 of 5
    16System.out.println("1. Keys only (keySet):");17for (String itemWater : prices.keySet()) {18    System.out.println("   • " + itemWater);19}
    output   • Water
    All 5 passes — pass 1 is the card above
    passitem
    1Water
    2Tea
    3Juice
    4Coffee
    5Soda
  3. total ← 0.0

    21// Method 2: Iterate values only  //#?values22System.out.println("\n2. Values only (values):");23double total→ 0.0 = 0;24for (Double price : prices.values()) {
    output
    2. Values only (values):
  4. total ← 1.5

    pass 1 of 5
    23double total = 0;24for (Double price1.5 : prices.values()) {25    total→ 1.5 += price1.5;26    System.out.printf("   $%.2f%n", price1.5);27}
    All 5 passes — pass 1 is the card above
    passpricetotal
    11.50.0 1.5
    23.01.5 4.5
    35.254.5 9.75
    44.59.75 14.25
    52.7514.25 17.0
  5. System.out.printf(" Total: $%.2f%n", total);

    27}28System.out.printf("   Total: $%.2f%n", total17.0);2930// Method 3: Iterate both (entrySet) - MOST COMMON  //#?entries31System.out.println("\n3. Keys and Values (entrySet):");32for (Map.Entry<String, Double> entry : prices.entrySet()) {
    output
    3. Keys and Values (entrySet):
  6. item ← Water, price ← 1.5

    pass 1 of 5
    31System.out.println("\n3. Keys and Values (entrySet):");32for (Map.Entry<String, Double> entryWater=1.5 : prices.entrySet()) {33    String item→ Water = entry.getKey();34    Double price→ 1.5 = entry.getValue();35    System.out.printf("   %-10s $%.2f%n", itemWater, price1.5);36}
    All 5 passes — pass 1 is the card above
    passentryitemprice
    1Water=1.5Water1.5
    2Tea=3.0Tea3.0
    3Juice=5.25Juice5.25
    4Coffee=4.5Coffee4.5
    5Soda=2.75Soda2.75
  7. cheapest ← null, expensive ← null, minPrice ← 1.7976931348623157E308

    38// Method 4: forEach with lambda (Java 8+)  //#?lambda39System.out.println("\n4. forEach lambda:");40prices.forEach((item, price) -> 41    System.out.printf("   %s → $%.2f%n", item, price)42);4344// Find max and min priced items45System.out.println("\n=== Price Analysis ===");46String cheapest→ null = null;47String expensive→ null = null;48double minPrice→ 1.7976931348623157E308 = Double.MAX_VALUE;49double maxPrice→ 4.9E-324 = Double.MIN_VALUE;
    output
    4. forEach lambda:
    
    === Price Analysis ===
  8. for (Map.Entry<String, Double> entry : prices.entrySet())

    pass 1 of 5
    51for (Map.Entry<String, Double> entryWater=1.5 : prices.entrySet()) {52    if (entry.getValue() < minPrice) {
    All 5 passes — pass 1 is the card above
    passentryminPricecheapest
    1Water=1.51.7976931348623157E308 1.5Water
    2Tea=3.0
    3Juice=5.25
    4Coffee=4.5
    5Soda=2.75
  9. minPrice ← 1.5, cheapest ← Water

    51for (Map.Entry<String, Double> entry : prices.entrySet()) {52    if (entry.getValue() < minPrice1.7976931348623157E308) {53        minPrice→ 1.5 = entry.getValue();54        cheapest→ Water = entry.getKey();55    }
  10. maxPrice ← 1.5, expensive ← Water

    pass 1 of 3
    55}56if (entry.getValue() > maxPrice4.9E-324) {57    maxPrice→ 1.5 = entry.getValue();58    expensive→ Water = entry.getKey();59}
    All 3 passes — pass 1 is the card above
    passmaxPriceexpensive
    14.9E-324 1.5Water
    21.5 3.0Tea
    33.0 5.25Juice
  11. System.out.printf("Cheapest: %s ($%.2f)%n", cheapest, minPrice);

    60    }61    System.out.printf("Cheapest: %s ($%.2f)%n", cheapestWater, minPrice1.5);62    System.out.printf("Most expensive: %s ($%.2f)%n", expensiveJuice, maxPrice5.25);63}

Use keySet(), values(), or entrySet() for different iteration needs.

Exercise: Getordefault.java

Use getOrDefault() and other convenience methods