From the documentation of Map.java -
The
Map.of()
andMap.ofEntries()
static factory methods provide a convenient way to cre
Java 9 introduced creating small unmodifiable Collection instances using a concise one line code, for maps the signature of factory method is:
static Map of(K k1, V v1, K k2, V v2, K k3, V v3)
This method is overloaded to have 0 to 10 key-value pairs, e.g.
Map map = Map.of("1", "first");
Map map = Map.of("1", "first", "2", "second");
Map map = Map.of("1", "first", "2", "second", "3", "third");
Similarly you can have up to ten entries.
For a case where we have more than 10 key-value pairs, there is a different method:
static Map ofEntries(Map.Entry extends K,? extends V>... entries)
Here is the usage.
Map map = Map.ofEntries(
new AbstractMap.SimpleEntry<>("1", "first"),
new AbstractMap.SimpleEntry<>("2", "second"),
new AbstractMap.SimpleEntry<>("3", "third"));