How to Update value in MultiValueMap for a specific key

3.6k Views Asked by At

I have a MultiValueMap like

{3=[c-2, c-2], 2=[b-1, b-1], 1=[a-1, a-2, a-3]}

At one point I have to update a single value of a specific key for example I have to update the key 2 like

2=[u-1,u-2]

how can i do this?

2

There are 2 best solutions below

0
On

I've never used that library - but I would expect these two examples to do what you need:

multiMap.getCollection(2).clear();
multiMap.putAll(2, Arrays.asList("u-1", "u-2"));

Or

Collection c = multiMap.getCollection(2);
c.clear();
Collections.addAll(c, "u-1", "u-2");
0
On

The safest way is to call getCollection() to retrieve the current mapping, remove(key) to clear that mapping, iterate the retrieved collection to re-insert values that you want to keep, and/or add the new values.

If you know the type of collection used for a mapping (because you've called the constructor that takes collectionFactory), you could get the collection and update it directly.