ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.
We used to use the unmodifiableMap() method of Collections class to create unmodifiable(immutable) Map. Map<String,String> map = new HashMap<String, String>(); Map<String,String> immutableMap = Collections. unmodifiableMap(map); Lets test this in JShell.
Mutable maps supports modification operations such as add, remove, and clear on it. Unmodifiable Maps are “read-only” wrappers over other maps. They do not support add, remove, and clear operations, but we can modify their underlying map.
Notice that your error message only contains five K, V
pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of()
methods, accepting between zero and five key-value pairings. There is not an of(...)
overload accepting a varags parameter because K
and V
can be different types.
You want an ImmutableMap.Builder
:
ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
.put("key1", "value1")
.put("key2", "value2")
.put("key3", "value3")
.put("key4", "value4")
.put("key5", "value5")
.put("key6", "value6")
.put("key7", "value7")
.put("key8", "value8")
.put("key9", "value9")
.build();
if the map is short you can do:
ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs
If it is longer then:
ImmutableMap.builder()
.put(key, value)
.put(key2, value2)
// ...
.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With