I have seen that ImmutableMap.of is used to create immutable map object. At the same time Java offers Map.of which creates immutable map as well. Is there any advantage of using ImmutableMap.of instead of Map.of from Java ?
Edit: I am not asking differences between map and immutable map. I am asking why some people prefer ImmutableMap.of instead of Map.of which also creates immutableMap.
Advertisement
Answer
I assume you are talking about com.google.common.collect.ImmutableMap
? According to the javadoc, that has been in guava since 2.0, which is really old (I can only find the year 2010 for version 3.0, so 2.0 is before that).
Map.of
was only introduced with java 9, which was released in September 2017. That means that only the first option was available before java 9, but you needed a library.
Since this feature was finally integrated into java itself with java 9 and you don’t need an external library anymore, I would argue Map.of
is preferrable.
However, in terms of readability, I have always hated that Map.of
as well as List.of
return immutable implementations, which is not what an inexperienced (=has not fallen into that trap yet) developer expects.
If you are using guava anyways, ImmutableMap.of
is the more readable option, but that’s up to you.