Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a key with an empty value to Guava Multimap

Tags:

multimap

guava

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?

like image 242
Ryan Nelson Avatar asked Jul 20 '12 22:07

Ryan Nelson


People also ask

Can a multimap have a null key?

The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an existing key-value pair has no effect. Keys and values may be null. All optional multimap methods are supported, and all returned views are modifiable.

How do you initialize a multimap in Java?

Another way to create a Multimap is to use the static method create() in the concrete classes that implement the interface (e.g., ArrayListMultimap<K, V> , LinkedListMultimap<K, V> , etc.): ListMultimap<String, Integer> m = ArrayListMultimap. create();

Does multimap maintain order?

One important thing to note about multimap is that multimap keeps all the keys in sorted order always.

How do I remove a multimap key in Java?

Remove/Replace existing keys/values in the Multimap Guava's MultiMap provides the remove() method that removes a single key-value pair from the multimap that matches the specified key-value pair. It returns true if the pair is removed; otherwise, it returns false if no such pair is found.


1 Answers

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

like image 176
Louis Wasserman Avatar answered Oct 18 '22 19:10

Louis Wasserman