Library contents

Java Map.replaceAll and Map.forEach

Use replaceAll to assign a new value to each existing key. Use forEach when visiting each mapping is enough.

A simple example

Map.replaceAll and Map.forEach

  1. Start with A = 1, B = 2
  2. Do this Add 1 to each value
  3. Result A = 2, B = 3
The transformation changes the values and preserves their keys.

Syntax

Java syntax
prices.replaceAll((item, price) -> price + 1)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Add a packing charge to each listed price

A café starts packing takeaway orders in reusable boxes. The manager adds one unit to each listed price and checks the new soup price before publishing the board.

Result5
Main.java
import java.util.HashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) throws Exception {
        var prices = new HashMap<>(Map.of("Soup", 4, "Salad", 6));
        prices.replaceAll((item, price) -> price + 1);
        System.out.println(prices.get("Soup"));
    }
}
Output
5

Every value rises by one while the menu keys stay the same.

Advertisements

Print delivery numbers in a predictable sequence

The warehouse must print delivery totals under the correct branch names. It sorts the branches by name before visiting each mapping so the printed report is repeatable.

First output lineEast 3
Main.java
import java.util.Map;
import java.util.TreeMap;

class Main {
    public static void main(String[] args) throws Exception {
        var branches = new TreeMap<>(Map.of("West", 2, "East", 3));
        branches.forEach((name, crates) -> System.out.println(name + " " + crates));
    }
}
Output
East 3
West 2

forEach visits each key-value pair in this TreeMap's key order.

Reprint stationery prices

A school shop increases every price by two credits. Every price gets the same increase. Find the revised value for the first item.

GivenPen 7 · increase 2
Worked result9

What to watch for

A calculation inside forEach does not by itself replace the mapping. Avoid structural edits to a map during iteration.

Documentation for Map.replaceAll and Map.forEach