Giorgi Gviani
Giorgi Gviani

Reputation: 28394

How to convert list to mutable map with pre processing in Scala?

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")

Upvotes: 4

Views: 6429

Answers (4)

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24593

Why not use foldLeft?

ids.foldLeft(mutable.Map.empty[String, String]) { (m, i) => 
  m += (s"foo:$i:bar" -> "val1")
}

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19753

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)

Upvotes: 0

tuxdna
tuxdna

Reputation: 8487

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.

Upvotes: 1

Jesper
Jesper

Reputation: 206896

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")): _*)

Upvotes: 12

Related Questions