Question

How to Iterate Through a HashMap in Java

javaloopshashmapiteration

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.

Take Quiz

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:

for (String name : scores.keySet()) {
    System.out.println(name + " -> " + scores.get(name));
}

3. Iterate over values with values()

Use this when you only care about the values.

for (Integer score : scores.values()) {
    System.out.println(score);
}

4. Java 8+ forEach()

Java 8 introduced a shorter style using lambdas.

scores.forEach((name, score) -> {
    System.out.println(name + " -> " + score);
});

This is concise and commonly used in modern Java code.

Which one should you choose?

  • Need key and value: use entrySet() or forEach()
  • Need only keys: use keySet()
  • Need only values: use values()

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:

  1. A HashMap named scores is created.
  2. Two entries are added:
    • key: "Alice", value: 90
    • key: "Bob", value: 85
  3. scores.entrySet() creates a view of all key-value pairs in the map.
  4. The for-each loop picks one entry at a time.
  5. On the first iteration, entry might represent Alice -> 90.
  6. entry.getKey() returns "Alice".
  7. entry.getValue() returns 90.
  8. The program prints Alice -> 90.
  9. On the next iteration, entry might represent Bob -> 85.
  10. The program prints Bob -> 85.

Important: because this is a HashMap, the actual order is not guaranteed. You should not rely on insertion order unless you use LinkedHashMap.

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.

Take Quiz

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

settings.forEach((key, value) -> System.out.println(key + "=" + value));

This is often used for short processing logic.

Choosing the right map type

In real code, developers also think about ordering:

  • HashMap: fast lookup, no guaranteed order
  • LinkedHashMap: preserves insertion order
  • TreeMap: sorted by key

The iteration technique is similar, but the order behavior changes.

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.

3. Trying to use indexes like a list

Broken code:

// Maps do not use numeric indexes like arrays or lists
// map.get(0);

A map uses keys, not positions.

4. Modifying the map incorrectly during iteration

Broken example:

for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    if (entry.getValue() < 50) {
        scores.remove(entry.getKey());
    }
}

This can cause a ConcurrentModificationException.

A safer approach is to use an iterator:

import java.util.Iterator;
import java.util.Map;

Iterator<Map.Entry<String, Integer>> iterator = scores.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    if (entry.getValue() < 50) {
        iterator.remove();
    }
}

5. Forgetting to import Map

If you use Map.Entry, you usually need:

import java.util.Map;

Comparisons

ApproachUse whenAccess to keyAccess to valueNotes
entrySet()You need both key and valueYesYesUsually the best general choice
keySet()You only need keysYesIndirectly via get()Less ideal if you need values too
values()You only need valuesNoYesSimple when keys do not matter
forEach()You want concise Java 8+ styleYesYesGood for short logic

HashMap vs other map types

Map typeOrder guaranteed?Typical use
HashMapNoGeneral-purpose key-value storage
LinkedHashMapYes, insertion orderWhen output order matters
TreeMapYes, sorted by keyWhen sorted keys are needed

entrySet() vs keySet()

If you need both key and value, entrySet() is usually better because:

  • it expresses your intent clearly
  • it avoids repeated lookups
  • it is the common Java style developers expect
Take Quiz

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

  • HashMap iteration order is not guaranteed
  • HashMap allows one null key and multiple null values
  • Removing items during a for-each loop can throw ConcurrentModificationException
  • Use an Iterator if you need safe removal during iteration

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 Iterator and call iterator.remove().

Why not treat a HashMap like an array?

Because a map stores data by key, not by numeric index. You access values using keys.

Take Quiz

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

  1. Create a HashMap<String, Integer> to store student names and scores.
  2. Add at least three students to the map.
  3. Iterate over the map and print each key-value pair.
  4. Iterate over the values and calculate the total score.
  5. Print the final total score.
Take Quiz

Keep learning

Related questions

View more