Adding a key with an empty value to Guava Multimap

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


As the javadoc covers, a multimap is conceptually a bunch of key-value pairs where the keys are not necessarily unique, for example a=1, a=2, b=3. If there are no values associated with a, then there are no key-value pairs for a, so a does not exist in the multimap.

One thing you can do is keep a separate Set<K> for the entire universe of keys you care about, or just to keep the additional keys that correspond to no values. Another is to use a Map<K, Collection<V>>, or a Map<K, Something> where Something contains a collection that might or might not be empty.

Tags:

Multimap

Guava