Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 424
Alexey Romanov Avatar asked May 17 '12 14:05

Alexey Romanov


People also ask

How do I create a Multimap?

Another way to create a Multimap is to use the static method create() in the concrete classes that implement the interface (e.g., ArrayListMultimap<K, V> , LinkedListMultimap<K, V> , etc.): ListMultimap<String, Integer> m = ArrayListMultimap. create();

How to declare Multimap in Java?

Following is a simple custom implementation of the Multimap class in Java using a Map and a Collection . * Add the specified value with the specified key in this multimap. * Returns the Collection of values to which the specified key is mapped, * or null if this multimap contains no mapping for the key.

What is ArrayListMultimap?

The ArrayListMultimap is a variation of a Map in which multiple values or objects are associated with a single key but it allows duplicate key/value pairs in the Map.


1 Answers

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.

like image 120
Daniel Teply Avatar answered Oct 03 '22 03:10

Daniel Teply