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

1

9

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?

Hagy answered 12/11, 2015 at 9:36 Comment(3)
put explicit generics for builder ImmutableMap.<String, String>builder().putAll(map1).putAll(map2).build()Figurative
thanks. I used an extra dot which gave me syntax error. ImmutableMap.<String, String>.builder().putAll(map1).putAll(map2).build()Hagy
@SimY4 consider posting your comment as an answer.Phenice
F
12

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();
Figurative answered 22/10, 2020 at 19:20 Comment(1)
I don't recommend using this in the case where you have duplicate keysStarspangled

© 2022 - 2024 — McMap. All rights reserved.