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?
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();
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With