I'm using the java immutables library.
@Value.Immutable
public interface Foo {
Map<Integer, String> getBar();
}
ImmutableFoo.builder().putBar(1, "asdf").putBar(1, "ghjk").build()
causes a duplicate key error. Is there any way to avoid this?
- If I happen upon the same key with a different value, I'd like to overwrite the old value with the new value.
- If I happen upon the same key with the same value, I'd like to ignore it.
The generated builder is intentionally doing this to prevent (actually detect early) accidental mistyping and copy-paste errors. In this, it actually mimics the behavior of Guava's
ImmutableMap.Builder
(which is actually used internally and is responsible for this error).To solve your problem, the best way to handle this is to create your own hash map, fill it with values in any order and with any number of duplicated/overriding entries, then use
builder.putAllBar(hashMap)
to apply it and turn it into immutable map during value object creation.The other option is to opt-out of using Guava, then generated code will use regular
HashMap
and will create defensive-copy wrapped inCollection.unmodifiableMap
for the immutable object. Use@Value.Style(jdkOnly = true)
to use only JDK-provided collections (read more about styles here: http://immutables.github.io/style.html). By using a regular hash map in a builder, you'll avoid having the duplicated key error.