Java HashMap forEach() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, forEach(action) calls action once for each mapping in a HashMap, passing the key and the value. The action is a BiConsumer<K, V>, usually written as a lambda such as (k, v) -> System.out.println(k + "=" + v).

It visits entries in the same internal order as entrySet(), which is not guaranteed. It is great for printing and collecting, but it has no way to remove the current entry.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. forEach(BiConsumer) was added in Java 8 as a default method of Map; HashMap overrides it to walk its table directly.

Syntax

Pass a lambda that takes a key and a value.

Java
Map<String, Integer> temps = new HashMap<>();
temps.put("Oslo", -3);
temps.forEach((city, t) -> System.out.println(city + ": " + t));
CallWhat it does
map.forEach((k, v) -> ...)Runs the lambda for every mapping.
new TreeMap<>(map).forEach(...)Same, but in sorted key order.
map.keySet().forEach(k -> ...)Keys only (the Iterable.forEach method).
map.values().forEach(v -> ...)Values only.

Local variables used inside the lambda must be effectively final. To accumulate a total, use a one-element array, an object field, or a plain for loop over entrySet().

Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public void forEach(BiConsumer<? super K, ? super V> action)

// Default method in Map<K, V>, overridden by HashMap

Parameters

ParameterDescription
action (BiConsumer<? super K, ? super V>)Code to run for each key and value. Must not be null.

Return Value

Return ValueDescription
voidNothing. Results must be collected by the action itself.

Compare with Similar Methods

Ways to loop over a map:

MethodHow it differs
entrySet()A classic loop; allows iterator.remove() and break.
keySet()Loop over keys only.
replaceAll(f)Use this to change every value instead.
values()Loop over values only.

Java Examples

Example 1 — Print City Temperatures with a Lambda

One line of code prints every key and value.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapForEachDemo {
    public static void main(String[] args) {
        Map<String, Integer> temps = new HashMap<>();
        temps.put("Lima", 18);
        temps.put("Oslo", -3);
        temps.put("Cairo", 24);

        temps.forEach((city, t) -> System.out.println(city + ": " + t + " C"));
    }
}

How It Works

  1. Two parameters. The lambda (city, t) -> ... matches BiConsumer<String, Integer>: the map passes each key as city and its value as t.
  2. No loop variable. There is no Map.Entry to declare; the map drives the iteration itself.
  3. Negative values print normally. Oslo's -3 is just another Integer value.
  4. Table order. Oslo's hash picks an earlier bucket than the others, so it prints first even though Lima was added first. Lima and Cairo share one bucket, and within it Lima, stored earlier, comes first.

Example 2 — Total Sales and Strong Regions

Accumulate a total in a one-element array and collect regions with sales of at least 100.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashMapForEachTotal {
    public static void main(String[] args) {
        Map<String, Integer> sales = new HashMap<>();
        sales.put("north", 120);
        sales.put("south", 80);
        sales.put("east", 150);
        sales.put("west", 95);

        int[] total = {0};
        List<String> strong = new ArrayList<>();
        sales.forEach((region, amount) -> {
            total[0] += amount;
            if (amount >= 100) {
                strong.add(region);
            }
        });

        Collections.sort(strong);
        System.out.println("total: " + total[0]);
        System.out.println("100 or more: " + strong);
    }
}

How It Works

  1. Effectively final. A lambda cannot reassign a local int, so the running total lives in total[0]; the array reference itself never changes.
  2. Block lambda. Curly braces let the action run two statements: add to the total and maybe record the region.
  3. Arithmetic. 120 + 80 + 150 + 95 = 445, and only north and east reach 100.
  4. Sort for stable output. The regions are collected in hash order, so Collections.sort fixes the order before printing.

Example 3 — HashMap Order vs TreeMap Order

Print the keys in the map's own order, then in sorted order through a TreeMap copy, and pass null as the action.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class HashMapForEachSorted {
    public static void main(String[] args) {
        Map<String, Integer> ranks = new HashMap<>();
        ranks.put("zeta", 3);
        ranks.put("alpha", 1);
        ranks.put("mid", 2);

        System.out.print("HashMap order:");
        ranks.forEach((k, v) -> System.out.print(" " + k));
        System.out.println();

        System.out.print("TreeMap order:");
        new TreeMap<>(ranks).forEach((k, v) -> System.out.print(" " + k));
        System.out.println();

        try {
            ranks.forEach(null);
        } catch (NullPointerException e) {
            System.out.println("forEach(null) -> NullPointerException");
        }
    }
}

How It Works

  1. One line, many prints. System.out.print keeps the keys on the same line, and the following println() ends it.
  2. Hash order. The HashMap visits zeta, alpha, mid, an order decided by the hash codes, not by the alphabet or by insertion.
  3. Sorted copy. new TreeMap<>(ranks) holds the same mappings sorted by key, and its forEach visits them alphabetically.
  4. No null action. Passing null instead of a lambda throws NullPointerException immediately.

Frequently Asked Questions

Pass a lambda with two parameters: map.forEach((key, value) -> System.out.println(key + "=" + value));
Not a local variable directly; locals used in a lambda must be effectively final. Use a one-element array, a field, or a regular loop.
No. Removing or adding keys causes ConcurrentModificationException. Use entrySet().removeIf(...) or an Iterator instead.
In the internal hash-table order, which is not guaranteed. Use new TreeMap<>(map).forEach(...) for sorted keys.
Java 8, together with lambda expressions.

Next: get()

Look up the value stored for a key.

get() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful