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?
Multimapdeliberately forbids this approach, and your proposed workaround is a no-op — it won’t actually do anything.The way
Multimapworks is thatmultimap.get(key)never returns null, but always returns some collection — possibly empty. (But the backingMultimapimplementation 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 thekeySet().Multimapis not aMap<K, Collection<V>>.)If you want to map to an empty collection, you must use
Map<K, List<V>>.