Java Map.ofEntries and Map.copyOf
Build an unmodifiable map from entries or snapshot an existing map. Map.copyOf takes the current key-value mappings.
A simple example
Map.ofEntries and Map.copyOf
- Start with A = 1
- Do this Copy the map, then set original A to 2
- Result Copy still has A = 1
Syntax
Map.copyOf(draft)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaKeep the price shown on yesterday's menu
A café changes its soup price after printing yesterday's menu. Accounts needs a snapshot of the earlier price to check old receipts even as the working price list changes.
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));
var printed = Map.copyOf(prices);
prices.put("Soup", 5);
System.out.println(printed.get("Soup"));
}
}
4
The snapshot still maps Soup to four after the working map changes.
Build the fixed price board from named entries
A kiosk prints a short menu with one price per item. A clerk can look up the salad price by its label without depending on the order in which the price board is stored.
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var menu = Map.ofEntries(Map.entry("Soup", 4), Map.entry("Salad", 6));
System.out.println(menu.get("Salad"));
}
}
6
Each entry defines one mapping. A direct key lookup returns the salad price.
Save a café price list
A counter freezes the morning menu before an afternoon update. The desk takes a snapshot before changing the working record. What value is visible on the saved copy?
What to watch for
These factories reject null keys and values. Map.ofEntries also rejects duplicate keys, and iteration order is unspecified.