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
Syntax
Map.of(k1, v1, k2, v2, ...)
Parameters
| Parameter | Description |
|---|---|
keys/valuesK, V, ... |
Alternating keys and values. |
Return value
An unmodifiable Map<K, V>.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 9 | Added |
Related
map.put()· Add a key-value pair, or replace the value if the key already exists. Returns the previous value or null.List.of()· Create an immutable list from values. Adding or removing later throws UnsupportedOperationException.- Java HashMap · tutorial