From the documentation of Map.java -
The
Map.of()
andMap.ofEntries()
static factory methods provide a convenient way to create immutable maps.
But when I already can use overloaded method ...
Map.of("k1","v1","k2","v2","k3","v3"...);
... what is the use of Map.ofEntries which also
returns an immutable map containing keys and values extracted from the given entries and the entries themselves are not stored in the map.
Any guesses on how would you create a Map of 26 elements?
The primary difference between the two factory methods in Map that you already linked is that :
Map.ofEntries
From the JEP-269:Convenience Factory Methods for Collections:
Your assumption about the method
.of()
from Map is somewhat incorrect probably because while this would compile with Java9:This, on the other hand, wouldn't:
The reason for that is since there is a varargs implementation for
List.of
andSet.of
but to create a similar API forMap
both the keys and values were supposed to be boxed as stated in the JEP as well. So, the same was created using varargs of typeMap.entry()
as:Furthermore from the documentation of
Map.entry()
which is also introduced Since:9 -which are similar to the characteristics of Immutable Map Static Factory Methods introduced recently.
Well it's very simple.
Map.of()
is not a varargs method. There are only overloadedMap.of()
for up to 10 entries. On the other hand,Map.ofEntries()
is a varargs method, hence allowing you to specify as many entries as you want.They could have just added
Map.ofEntries()
but since many times you only need just a few entries, they also included theMap.of()
versions as convenience methods so that you don't need to wrap each key-valur pair inside anEntry
.Java 9 introduced creating small unmodifiable Collection instances using a concise one line code, for maps the signature of factory method is:
This method is overloaded to have 0 to 10 key-value pairs, e.g.
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:
Here is the usage.