How to replace a value inside a MultiValueMap<String, List> in Java?

  Kiến thức lập trình

I am using org.springframework.util.MultiValueMap.

As a parameter I am passed a MultiValueMap<String, List<?>> multimap. My example here won’t utilize having multiple values per each key, but it’s used in my other code so I have to keep it as a MultiValueMap and not a regular Map. For this example, my multivaluemap just looks like a regular map:

{
"var1"=["to replace"], 
"var2"=["hey"]
}

I want to replace the list for var1.

My code looks like this:

String str = "a new string";
multimap.set("var1", Collections.singletonList(str));
System.out.println(multimap.get("var1");
System.out.println(multimap.get("var2");

So getting and printing “var2” returns how I want it to because I never replaced it, printing: [hey]

But getting “var1” immediately after, prints out this: [[a new string]]

This makes any of my other code that uses this map not work. I think what I’m doing right now is incorrectly replacing the original string value with a list? But if I simply do multimap.set("var1", str); it will not run.

How do I set the value for “var1” in the MultiValueMap so that it is a List rather than a List of Lists?

LEAVE A COMMENT