Arrays & Collections
HashMap
Key-Value Storage
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.
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));
}
}
}
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 ===for (String key : phoneBook.keySet())
pass 1 of 636System.out.println("\n=== All Contacts ===");37for (String keyBob : phoneBook.keySet()) {38 System.out.println(keyBob + ": " + phoneBook.get(key));39}outputBob: 555-5678All 6 passes — pass 1 is the card above pass key1 Bob 2 Eve 3 Alice 4 David 5 Carol 6 Frank
HashMap<String, String> maps string keys to string values. Use put() to add.
Look up a contact
Retrieve a value by its key.
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);
}
}
}
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: Bananasif (stock != null)
22if (stock30 != null) { //#?nullcheck23 System.out.println("In stock: " + stock30 + " units");outputIn stock: 30 unitsif (stock < 35)
25if (stock30 < 35) {26 System.out.println("⚠️ Low stock - consider reordering!");27}output⚠️ Low stock - consider reordering!String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};
33// Using getOrDefault //#?default34System.out.println("\n=== Using getOrDefault ===");35String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};output === Using getOrDefault ===qty ← 50, status ← ✓ 50 in stock
pass 1 of 437for (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 stockAll 4 passes — pass 1 is the card above pass checkItemqtystatus1 Apples 50 ✓ 50 in stock 2 Mangoes 0 ✗ Not available 3 Oranges 25 ✓ 25 in stock 4 Pears 0 ✗ Not available
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: Mangoeselse
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]String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};
32// Using getOrDefault33System.out.println("\n=== Using getOrDefault ===");34String[] checkItems = {"Apples", "Mangoes", "Oranges", "Pears"};output === Using getOrDefault ===qty ← 50, status ← ✓ 50 in stock
pass 1 of 436for (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 stockAll 4 passes — pass 1 is the card above pass checkItemqtystatus1 Apples 50 ✓ 50 in stock 2 Mangoes 0 ✗ Not available 3 Oranges 25 ✓ 25 in stock 4 Pears 0 ✗ Not available
get(key) returns the value, or null if key doesn't exist.
Update an entry
Change the value associated with a key.
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);
}
}
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 ===count ← 0
pass 1 of 740for (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 pass wordcount1 apple 0 2 banana 0 3 apple 1 4 orange 0 5 apple 2 6 banana 1 7 grape 0 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.
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);
}
}
}
}
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: bobcorrectPassword ← 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 foundif (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!weakPassword ← pass123
38// Check both key and value //#?containsval39System.out.println("\n=== Security Check ===");40String weakPassword→ pass123 = "pass123";output === Security Check ===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!for (String user : userPasswords.keySet())
pass 1 of 346// 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 pass userweakPassword1 carol — 2 bob — 3 alice pass123 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
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: eveelse
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?weakPassword ← pass123
37// Check both key and value38System.out.println("\n=== Security Check ===");39String weakPassword→ pass123 = "pass123";output === Security Check ===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!for (String user : userPasswords.keySet())
pass 1 of 345// 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 pass userweakPassword1 carol — 2 bob — 3 alice pass123 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.
Iterate through entries
Loop through all keys, values, or key-value pairs.
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);
}
}
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):for (String item : prices.keySet())
pass 1 of 516System.out.println("1. Keys only (keySet):");17for (String itemWater : prices.keySet()) {18 System.out.println(" • " + itemWater);19}output • WaterAll 5 passes — pass 1 is the card above pass item1 Water 2 Tea 3 Juice 4 Coffee 5 Soda 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):total ← 1.5
pass 1 of 523double 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 pass pricetotal1 1.5 0.0 → 1.5 2 3.0 1.5 → 4.5 3 5.25 4.5 → 9.75 4 4.5 9.75 → 14.25 5 2.75 14.25 → 17.0 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):item ← Water, price ← 1.5
pass 1 of 531System.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 pass entryitemprice1 Water=1.5 Water 1.5 2 Tea=3.0 Tea 3.0 3 Juice=5.25 Juice 5.25 4 Coffee=4.5 Coffee 4.5 5 Soda=2.75 Soda 2.75 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 ===for (Map.Entry<String, Double> entry : prices.entrySet())
pass 1 of 551for (Map.Entry<String, Double> entryWater=1.5 : prices.entrySet()) {52 if (entry.getValue() < minPrice) {All 5 passes — pass 1 is the card above pass entryminPricecheapest1 Water=1.5 1.7976931348623157E308 → 1.5 Water 2 Tea=3.0 — — 3 Juice=5.25 — — 4 Coffee=4.5 — — 5 Soda=2.75 — — 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 }maxPrice ← 1.5, expensive ← Water
pass 1 of 355}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 pass maxPriceexpensive1 4.9E-324 → 1.5 Water 2 1.5 → 3.0 Tea 3 3.0 → 5.25 Juice 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