Library contents

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

  1. Start with A = 1
  2. Do this Copy the map, then set original A to 2
  3. Result Copy still has A = 1
The change in the original does not replace the entry in the copy.

Syntax

Java syntax
Map.copyOf(draft)
Run these examples in Java

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

java Main.java

Keep 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.

Result4
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));
        var printed = Map.copyOf(prices);
        prices.put("Soup", 5);
        System.out.println(printed.get("Soup"));
    }
}
Output
4

The snapshot still maps Soup to four after the working map changes.

Advertisements

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.

Result6
Main.java
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"));
    }
}
Output
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?

GivenMorning soup 4 · later 6
Worked result4

What to watch for

These factories reject null keys and values. Map.ofEntries also rejects duplicate keys, and iteration order is unspecified.

Documentation for Map.ofEntries and Map.copyOf