You can use entrySet() with an enhanced for loop to read each key-value pair in a HashMap.
In this example, you will store product names and their quantities, then print each entry.
Source code
Save the following code as HashMapLoopExample.java:
import java.util.HashMap;
import java.util.Map;
public class HashMapLoopExample {
void main() {
Map<String, Integer> inventory = new HashMap<>();
inventory.put("Notebook", 12);
inventory.put("Pen", 30);
inventory.put("Pencil", 20);
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
String product = entry.getKey();
int quantity = entry.getValue();
IO.println(product + ": " + quantity);
}
IO.println("Total products: " + inventory.size());
}
}
Explanation
A map stores values associated with unique keys. In this example, each product name is a key, and its quantity is the corresponding value:
Map<String, Integer> inventory = new HashMap<>();
The type arguments specify that keys are strings and values are integers. Java generics use reference types, so the value type is Integer rather than int.
Adding entries
Use put() to add a key-value pair:
inventory.put("Notebook", 12);
Java automatically boxes the quantity into an Integer.
If you call put() again with an existing key, the new value replaces the previous value for that key.
Reading entries with entrySet()
The entrySet() method provides a set view of the map’s entries:
inventory.entrySet()
Each entry contains both a key and its associated value. The enhanced for loop reads one entry at a time:
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
Inside the loop, use getKey() and getValue() to access the pair:
String product = entry.getKey();
int quantity = entry.getValue();
Assigning the Integer value to an int automatically unboxes it. All values in this example are non-null.
Using entrySet() lets you read the key and value together without performing a separate lookup with get().
Counting entries
The size() method returns the number of key-value pairs:
inventory.size()
Here, the result is 3. It counts product entries, not the sum of their quantities.
Run the example
Compile and run the file:
javac HashMapLoopExample.java
java HashMapLoopExample
Example output
Notebook: 12
Pen: 30
Pencil: 20
Total products: 3
A HashMap does not guarantee iteration order, so the product lines may appear in a different order.
Using forEach()
For a shorter alternative, replace the loop with:
inventory.forEach((product, quantity) ->
IO.println(product + ": " + quantity));
This passes each key and value to the lambda expression. It also follows the map’s iteration order, which remains unspecified for a HashMap.
