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
- Start with A = 1, B = 2
- Do this Add 1 to each value
- Result A = 2, B = 3
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.javaAdd 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.
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"));
}
}
5
Every value rises by one while the menu keys stay the same.
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.
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));
}
}
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.
What to watch for
A calculation inside forEach does not by itself replace the mapping. Avoid structural edits to a map during iteration.