Java 25 (LTS) reference · Map and HashMap Methods

Java Map.of() Method

Create an immutable map from key-value pairs (up to 10 pairs; Map.ofEntries() for more). No null keys or values.

Java 25 (LTS) Since Java 9

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

Map.of(k1, v1, k2, v2, ...)

Parameters

ParameterDescription
keys/values
K, V, ...
Alternating keys and values.

Return value

An unmodifiable Map<K, V>.

Examples

An immutable map
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = Map.of("mug", 12, "tea", 3);
        System.out.println(stock.get("mug") + " mugs");
        System.out.println(new TreeMap<>(stock));  // sorted by key for display
    }
}

Output

12 mugs
{mug=12, tea=3}

Run this on your computer — see “Get Started” for setup.

Immutability
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> fixed = Map.of("a", 1);
        try {
            fixed.put("b", 2);
        } catch (UnsupportedOperationException e) {
            System.out.println("Map.of maps are immutable");
        }
    }
}

Output

Map.of maps are immutable

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 9Added

Was this page helpful?