Alexey Romanov Alexey Romanov - 4 months ago 28
Java Question

Compact way to create Guava Multimaps?

If I want to create a new Multimap with simple defaults, I curently need to do something like:

private final Multimap<Key, Value> providersToClasses = Multimaps
.newListMultimap(
new HashMap<Key, Collection<Value>>(),
new Supplier<List<Value>>() {
@Override
public List<Value> get() {
return Lists.newArrayList();
}
});


because Java can't infer the correct types if
Maps.newHashMap
is used for the backing map. Of course, this can be refactored into a separate method, but is there already a way to write it more concisely?

Answer

Why aren't you using ArrayListMultimap.create() for such a simple case? It's the default way to create the simple HashMap/ArrayList that is probably the most common used multimap.