18

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?

Ryan Nelson
  • 4,466
  • 5
  • 29
  • 45
  • 2
    How about you tell us *why* you feel you need to make a Multimap behave in a way it wasn't intended? – Jon Skeet Jul 20 '12 at 22:57
  • 5
    It's just the nature of the data. I have a set of keys, some of which have values associated with them, and a few who don't. (The actual keys/values come from a DB). If this is a bad use case for Multimap, that's fine, I'm open to other solutions. The original impl in this code used a Map> and switching to Multimap seemed natural. – Ryan Nelson Jul 20 '12 at 23:13

2 Answers2

27

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

Martin
  • 3,703
  • 2
  • 21
  • 43
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
8

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.

Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
Kevin Bourrillion
  • 40,336
  • 12
  • 74
  • 87