Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 720
Elad Benda Avatar asked Nov 12 '15 09:11

Elad Benda


1 Answers

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();
like image 63
SimY4 Avatar answered Oct 14 '22 00:10

SimY4