To instantiate BiMap Of google-collections in Java

Another cool way to create a BiMap, but in this case an immutable BiMap, is using the ImmutableBiMap.Builder.

static final ImmutableBiMap<String, Integer> WORD_TO_INT =
   new ImmutableBiMap.Builder<String, Integer>()
       .put("one", 1)
       .put("two", 2)
       .put("three", 3)
       .build();

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableBiMap.html


As stated in the linked question, you are supposed to use the create() factory methods.

In your case, this means changing

this.wordToWordID = new BiMap<String. Integer>();

to

this.wordToWordID = HashBiMap.create(); 

BiMap is an interface, and as such cannot be instantiated. You need to instantiate a concrete subclass according to the properties you want, available subclasses (according to the javadoc) are EnumBiMap, EnumHashBiMap, HashBiMap, ImmutableBiMap.

Tags:

Java

Guava

Bimap