Map.of()
Creates an unmodifiable map from key and value pairs.
Available since: Java 9
Syntax
static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, ...)Parameters
| Parameter | Type | Description |
|---|---|---|
| k1, v1, ... | K, V | Key and value pairs, at most 10 pairs; keys must not repeat, `null` is forbidden. |
Return value
Map<K, V>An unmodifiable map.
Examples
A small price table:
void main() {
Map<String, Integer> prices = Map.of("tea", 3, "coffee", 4);
IO.println(prices.get("coffee"));
IO.println(prices.containsKey("juice"));
}Output:
4
falseMore than ten pairs — with Map.ofEntries():
void main() {
Map<Integer, String> codes = Map.ofEntries(
Map.entry(200, "OK"),
Map.entry(404, "Not Found"),
Map.entry(500, "Server Error")
);
IO.println(codes.get(404));
}Output:
Not FoundNotes
The iteration order of Map.of() is unspecified and changes between runs — to print in order use TreeMap or LinkedHashMap. Changes throw UnsupportedOperationException and a duplicate key throws IllegalArgumentException. A modifiable copy: new HashMap<>(Map.of(...)).
See also
Related recipes
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.