Iterate with keySet()
Part of the Logic & Flow section of Coddy's Java journey — lesson 17 of 59.
Iterating with keySet() means you obtain a set of all the keys in the HashMap and then use the get() method to fetch the corresponding values. This is simple and works well for small maps.
First, create a HashMap of products:
HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("Laptop", 10);
inventory.put("Mouse", 50);
inventory.put("Keyboard", 30);Now, iterate using keySet():
for (String product : inventory.keySet()) {
int quantity = inventory.get(product);
System.out.println("Product: " +
product + ", Quantity: " + quantity);
}
// Product: Laptop, Quantity: 10
// Product: Mouse, Quantity: 50
// Product: Keyboard, Quantity: 30Challenge
EasyCreate a method named <strong>printInventoryKeySet</strong> that accepts a HashMap (where keys are product names and values are quantities) from a JSON string read via Scanner. Your method should iterate over the HashMap using the keySet() method and print each key-value pair in the format:
Product: <product name>, Quantity: <quantity>Cheat sheet
Use keySet() to iterate over HashMap keys and get() to fetch corresponding values:
HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("Laptop", 10);
inventory.put("Mouse", 50);
inventory.put("Keyboard", 30);
for (String product : inventory.keySet()) {
int quantity = inventory.get(product);
System.out.println("Product: " + product + ", Quantity: " + quantity);
}Try it yourself
import java.util.HashMap;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static void printInventoryKeySet(HashMap<String, Integer> inventory) {
// Write your code here using keySet()
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read JSON string input representing the inventory HashMap
String inventoryString = scanner.nextLine();
// Convert JSON string to HashMap<String, Integer>
Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
HashMap<String, Integer> inventory = new Gson().fromJson(inventoryString, mapType);
printInventoryKeySet(inventory);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow