Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 881
user52028778 Avatar asked Sep 16 '25 12:09

user52028778


2 Answers

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")): _*)
like image 67
Jesper Avatar answered Sep 19 '25 05:09

Jesper


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.

like image 41
tuxdna Avatar answered Sep 19 '25 04:09

tuxdna