Adding a key with an empty value to Guava Multimap

Ryan Nelson picture Ryan Nelson · Jul 21, 2012 · Viewed 7.8k times · Source

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?

Answer

Louis Wasserman picture Louis Wasserman · Jul 21, 2012

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>>.