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
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));
        }
    }
}

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.

Lookup.java
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 = ;
        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 = ;
        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);
        }
    }
}

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

Update an entry

Change the value associated with a key.

UpdateEntry.java
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);
    }
}

put() with existing key replaces the old value.

Check if key exists

Test whether a key is in the map before accessing.

CheckKey.java
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 = ;
        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 = ;
        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);
            }
        }
    }
}

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
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);
    }
}

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

Exercise: Getordefault.java

Use getOrDefault() and other convenience methods