I want to add, remove and replace values in a MultiMap provided by Guava.
I do this currently to add values..
static Multimap<Integer, Float> myMultimap; myMultimap = ArrayListMultimap.create(); myMultimap.put(1, (float)4.3); myMultimap.put(2, (float)4.9); myMultimap.put(1, (float)4.7); myMultimap.put(1, (float)4.5);
Removing values is easier with Guava library.
myMultimap.remove(1,(float)4.7);
But how can I use the replaceValues method?
I mean this
myMultimap.replaceValues(1, (float)4.3);
Say I wanted to replace value 4.3 with a new value 5.99, how should I do that, the method expects some Iterable function and I am not sure as of how to implement it..
This is the error..
The method replaceValues(Integer, Iterable) in the type Multimap is not applicable for the arguments (int, float)
Advertisement
Answer
Multimap.replaceValues
takes a collection of values that replaces all of the existing values for the given key. From the JavaDoc it looks like you need to use remove
followed by put
.
If the map is modifiable, you can get a modifiable view on the collection of values mapped to a single key using get
, but the view returned is a plain Collection
without an atomic replace method. You can always create your own helper method. Note that this method is not thread-safe.
public static <K,V> boolean replaceValue(Multimap<K,V> map, K key, V oldValue, V newValue) { if (map.remove(key, oldValue)) { map.put(key, newValue); return true; } return false; }