I have a need to add a key to a Guava Multimap with an empty collection as the value. How do I accomplish this?
I tried this:
map.put( "my key", null );
but calling get() returns a list with one element, which is null. I worked around this by doing the following:
map.putAll("my key2", new ArrayList())
but I'm wondering if this is a bad thing to do? I know Guava automatically removes a key when the last value is removed to keep containsKey() consistent. What's my best option here?
The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an existing key-value pair has no effect. Keys and values may be null. All optional multimap methods are supported, and all returned views are modifiable.
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();
One important thing to note about multimap is that multimap keeps all the keys in sorted order always.
Remove/Replace existing keys/values in the Multimap Guava's MultiMap provides the remove() method that removes a single key-value pair from the multimap that matches the specified key-value pair. It returns true if the pair is removed; otherwise, it returns false if no such pair is found.
Multimap
deliberately forbids this approach, and your proposed workaround is a no-op -- it won't actually do anything.
The way Multimap
works is that multimap.get(key)
never returns null, but always returns some collection -- possibly empty. (But the backing Multimap
implementation probably doesn't actually store anything for that key, and if a key isn't mapped to a nonempty collection, it won't e.g. appear in the keySet()
. Multimap
is not a Map<K, Collection<V>>
.)
If you want to map to an empty collection, you must use Map<K, List<V>>
.
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