Search code examples
javahashmaphashtableimmutability

how to combine two ImmutableMap<String,String> in Java 8?


I have tried this code:

    final ImmutableMap<String, String> map1 = ImmutableMap.of("username", userName, "email", email1, "A", "A1",
            "l", "500L");
    final ImmutableMap<String, String> map2 = ImmutableMap.of("b", "ture", "hashed_passwords", "12345", "e",
            "TWO", "fakeProp", "fakeVal");

    final ImmutableMap<String, String> map3 = ImmutableMap.builder().putAll(map1).putAll(map2).build();

but got an error:

Error:(109, 105) java: incompatible types: com.google.common.collect.ImmutableMap<java.lang.Object,java.lang.Object> cannot be converted to com.google.common.collect.ImmutableMap<java.lang.String,java.lang.String>

how can I cast it otherwise?


Solution

  • Java type inference is not always as good as we all wish it could be. Sometimes, you need to provide type hints for it to be able to figure things out.

    In your case you need to provide explicit generic types for ImmutableMap builder method.

    ImmutableMap.<String, String>builder()
        .putAll(map1)
        .putAll(map2)
        .build();