问题
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?
回答1:
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>>
.
回答2:
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.
来源:https://stackoverflow.com/questions/11587895/adding-a-key-with-an-empty-value-to-guava-multimap