2

I need to initialize an ImmutableMap (guava 21.0) and I need it to resolve to a Map> for this example I will just use String.

So I have:

import com.google.common.collect.ImmutableMap;
public class MyClass {
    private Map<String,String> testMap = 
         ImmutableMap<String,String>.builder().put("a","b").build();

and on that last line I get a huge amount of compiler errors. The use of ImmutableMap<String,String>.of() gets the same result.

If I remove I just get one error, a type mismatch.

How can I use ImmutableMap for explicit (literal-like) initialization when I do want a map with explicit types?

Mikhail Ramendik
  • 1,063
  • 2
  • 12
  • 26

2 Answers2

9

Place generic types after the dot:

private Map<String, String> testMap = 
    ImmutableMap.<String, String>builder().put("a","b").build();

See great Angelika Langer's Generics FAQ section on "What is explicit type argument specification?" for more details.

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
  • 1
    Coming from C# this is very difficult to remember, thanks @Xaerxess for helping me out of a pit of frustration! – JamieS Jul 10 '18 at 17:15
1

In case you don't need to use the builder, there's no need to specify generic type parameters either.

Just use:

Map<String, String> map = ImmutableMap.of("a", "b");

Generic type parameters will be inferred by the compiler.

If, on the other hand, you need to use the builder, then the answer from @Xaerxess explains what you have to do.

fps
  • 33,623
  • 8
  • 55
  • 110
  • 1
    True, but OP started with builder, which still requires explicit types and is needed for bigger maps (and for readability in such cases). – Grzegorz Rożniecki May 09 '17 at 14:55
  • 1
    @Xaerxess You are absolutely correct. I upvoted your answer, which answers OP's question directly. My answer is intended to be a complement to yours. I will rewrite it to make this more clear. – fps May 09 '17 at 15:53