Question
I want to understand the best way to iterate over the items in a HashMap in Java.
For example, given a map with keys and values, what is the recommended and efficient way to loop through its contents?
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
How should I iterate through all entries in this HashMap?
Short Answer
By the end of this page, you will understand how to iterate through a HashMap in Java using entrySet(), keySet(), values(), and forEach(). You will also learn which approach is usually the best, when to use each one, and common mistakes to avoid.
Concept
A HashMap in Java stores data as key-value pairs. Iterating through a HashMap means visiting each stored item so you can read or process its key, its value, or both.
The most important idea is that a map is not a list. You do not access it by numeric index like an array or ArrayList. Instead, you work with:
- the keys using
keySet() - the values using
values() - the entries using
entrySet()
An entry is one complete key-value pair.
In real programs, iterating through a map is common when you need to:
- print configuration settings
- count frequencies
- transform data
- validate input
- build reports
- process lookup tables
In most cases, if you need both the key and value, the best choice is entrySet() because it is clear and efficient.
HashMap does not guarantee order. If iteration order matters, you may need a different map type such as LinkedHashMap or TreeMap.
Mental Model
Think of a HashMap like a dictionary:
- the word is the key
- the definition is the value
If you want to go through the whole dictionary, you have a few options:
- look at every word only
- look at every definition only
- look at each word and definition together
That is exactly what keySet(), values(), and entrySet() do.
If you need the full dictionary entry, it makes most sense to iterate over the full pair instead of looking up the definition again from the word.
Syntax and Examples
1. Recommended: iterate with entrySet()
If you need both the key and the value, this is the standard approach.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
This loops through each key-value pair directly.
2. Iterate over keys with keySet()
Use this when you only need the keys.
for (String name : scores.keySet()) {
System.out.println(name);
}
You can also get the value from the key, but this is usually not the best choice if you need both:
Step by Step Execution
Consider this example:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
Step by step:
- A
HashMapnamedscoresis created. - Two entries are added:
- key:
"Alice", value:90 - key:
"Bob", value:85
- key:
scores.entrySet()creates a view of all key-value pairs in the map.- The
for-eachloop picks one entry at a time. - On the first iteration,
entrymight representAlice -> 90. entry.getKey()returns"Alice".entry.getValue()returns .
Real World Use Cases
Iterating through a HashMap appears in many real programs.
Configuration processing
Map<String, String> config = new HashMap<>();
config.put("host", "localhost");
config.put("port", "8080");
for (Map.Entry<String, String> entry : config.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Used for reading app settings or environment-based options.
Counting frequencies
Map<String, Integer> wordCounts = new HashMap<>();
wordCounts.put("java", 3);
wordCounts.put("map", 2);
for (Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
System.out.println(entry.getKey() + " appears " + entry.getValue() + " times");
}
Used in text analysis, logs, and reporting.
API response processing
A map may store fields from parsed JSON or request parameters. Iteration lets you validate or transform each field.
Data aggregation
Maps are often used to group totals by category, such as sales by product or users by country.
Real Codebase Usage
In real projects, developers usually choose the iteration style based on what they need from the map.
Common pattern: use entrySet() for full access
for (Map.Entry<String, String> entry : headers.entrySet()) {
String headerName = entry.getKey();
String headerValue = entry.getValue();
System.out.println(headerName + ": " + headerValue);
}
This is common in request headers, configuration maps, and cached values.
Validation while iterating
for (Map.Entry<String, String> entry : formData.entrySet()) {
if (entry.getValue() == null || entry.getValue().isBlank()) {
System.out.println("Missing value for: " + entry.getKey());
}
}
Guard-clause style inside loops
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
if (entry.getValue() < 0) {
continue;
}
System.out.println(entry.getKey() + " passed validation");
}
Modern Java style with forEach
Common Mistakes
1. Using keySet() when you need both key and value
This works, but is less ideal than entrySet().
for (String key : scores.keySet()) {
System.out.println(key + " -> " + scores.get(key));
}
Prefer:
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
2. Expecting a HashMap to keep insertion order
Broken assumption:
HashMap<String, Integer> map = new HashMap<>();
map.put("first", 1);
map.put("second", 2);
map.put("third", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey());
}
Do not assume the output will always be first, second, third.
If order matters, use LinkedHashMap.
Comparisons
| Approach | Use when | Access to key | Access to value | Notes |
|---|---|---|---|---|
entrySet() | You need both key and value | Yes | Yes | Usually the best general choice |
keySet() | You only need keys | Yes | Indirectly via get() | Less ideal if you need values too |
values() | You only need values | No | Yes | Simple when keys do not matter |
forEach() | You want concise Java 8+ style | Yes |
Cheat Sheet
Quick reference
Iterate over key-value pairs
for (Map.Entry<K, V> entry : map.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
}
Iterate over keys only
for (K key : map.keySet()) {
}
Iterate over values only
for (V value : map.values()) {
}
Java 8+ lambda style
map.forEach((key, value) -> {
System.out.println(key + " -> " + value);
});
Rules of thumb
- Need both key and value: use
entrySet() - Need only keys: use
keySet() - Need only values: use
values() - Need concise syntax: use
forEach() - Need predictable order: do not rely on
HashMap
Edge cases
FAQ
What is the best way to iterate over a HashMap in Java?
Usually, entrySet() is the best choice when you need both the key and the value.
Should I use keySet() or entrySet()?
Use keySet() if you only need keys. Use entrySet() if you need both keys and values.
Does HashMap preserve insertion order while iterating?
No. HashMap does not guarantee iteration order. Use LinkedHashMap if order matters.
Can I iterate over only the values in a map?
Yes. Use map.values().
Is forEach() better than a normal loop?
Not always. forEach() is shorter and modern, but a normal for-each loop can be easier to read for longer logic.
Can I remove items from a HashMap while iterating?
Not directly with a for-each loop. Use an and call .
Mini Project
Description
Build a small Java program that stores student scores in a HashMap and prints a simple report. This project demonstrates how to iterate over keys, values, and full entries, which is a very common pattern in real applications that manage lookup data.
Goal
Create a program that stores several student scores and prints each student's name with their score, then calculates the total of all scores.
Requirements
- Create a
HashMap<String, Integer>to store student names and scores. - Add at least three students to the map.
- Iterate over the map and print each key-value pair.
- Iterate over the values and calculate the total score.
- Print the final total score.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.