4

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")
user52028778
  • 27,164
  • 3
  • 36
  • 42

4 Answers4

12

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")): _*)
Community
  • 1
  • 1
Jesper
  • 202,709
  • 46
  • 318
  • 350
1

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.

tuxdna
  • 8,257
  • 4
  • 43
  • 61
1

Why not use foldLeft?

ids.foldLeft(mutable.Map.empty[String, String]) { (m, i) => 
  m += (s"foo:$i:bar" -> "val1")
}
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219
0

Try Like this:

scala> import scala.collection.mutable
scala> val result = mutable.Map[String, String]()
result: scala.collection.mutable.Map[String,String] = Map()

scala> val ids = List(7, 8, 9)
ids: List[Int] = List(7, 8, 9)

scala> for(x <- ids){
     | result("foo:%d:bar".format(x)) = "val1"
     | }

scala> result
res3: scala.collection.mutable.Map[String,String] = Map(foo:9:bar -> val1, foo:7:bar -> val1, foo:8:bar -> val1)
Hackaholic
  • 19,069
  • 5
  • 54
  • 72