Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
k1, v1, ...K, VKey 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
false

More 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 Found

Notes

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

  • HashMap — A map backed by a hash table: fast lookup by key, no guaranteed order.
  • Map.Entry — A single key and value pair of a map.
  • List.of() — Creates an unmodifiable list from the listed elements.
  • Set.of() — Creates an unmodifiable set from the listed elements.

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.

Thanks for reading!

Donate to the site — we work hard for you.