Menu
Coddy logo textTech

Iterate with entrySet()

Part of the Logic & Flow section of Coddy's Java journey — lesson 18 of 59.

Iterating with entrySet() means obtaining a set of Map.Entry objects from the HashMap. Each Map.Entry provides both the key and its corresponding value, making it more efficient since it avoids the extra lookup required with keySet().

Create a HashMap:

HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("Laptop", 10);
inventory.put("Mouse", 50);
inventory.put("Keyboard", 30);

Iterate using entrySet():

for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
   System.out.println("Product: " +
   entry.getKey() + ", Quantity: " +
   entry.getValue());
}
// Product: Laptop, Quantity: 10
// Product: Mouse, Quantity: 50
// Product: Keyboard, Quantity: 30
challenge icon

Challenge

Easy

Create a method named <strong>printInventoryEntrySet</strong> that accepts a HashMap (with product names as keys and quantities as values) from a JSON string read via Scanner. Your method should iterate over the HashMap using the entrySet() method and print each key-value pair in the format:

Product: <product name>, Quantity: <quantity>

Try it yourself

import java.util.HashMap;
import java.util.Map;
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 printInventoryEntrySet(HashMap<String, Integer> inventory) {
        // Write your code here using entrySet()
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        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);

        printInventoryEntrySet(inventory);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow