I have a list (size of the list is variable):
val ids = List(7, 8, 9)
and would like to get the following map:
val result= Map("foo:7:bar" -> "val1",
"foo:8:bar" -> "val1",
"foo:9:bar" -> "val1")
everything in the map is hard-coded except ids and value is the same for everyone, but map has to be mutable, I'd like to update one of its values later:
result("foo:8:bar") = "val2"
val result= Map("foo:7:bar" -> "val1",
"foo:8:bar" -> "val2",
"foo:9:bar" -> "val1")
You can do that like this: First map over the list to produce a list of tuples, then call toMap
on the result which will make an immutable Map
out of the tuples:
val m = ids.map(id => ("foo:" + id + ":bar", "val1")).toMap
Then convert the immutable Map
to a mutable Map
, for example like explained here:
val mm = collection.mutable.Map(m.toSeq: _*)
edit - the intermediate immutable Map
is not necessary as the commenters noticed, you can also do this:
val mm = collection.mutable.Map(ids.map(id => ("foo:" + id + ":bar", "val1")): _*)
Try this:
import scala.collection.mutable
val ids = List(7, 8, 9)
val m = mutable.Map[String, String]()
ids.foreach { id => m.update(s"foo:$id:bar", "val1") }
scala> m
Map(foo:9:bar -> val1, foo:7:bar -> val1, foo:8:bar -> val1)
You, don't need to create any intermediate objects, that map
does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With