How do I create a List by applying an operation to all elements of a scala Map? -
How do I create a List by applying an operation to all elements of a scala Map? -
i have scala map mymap
, want create list mylist
of pairs follows:
for each (k,v) in mymap, mylist should have tuple (v.somemember, k) element
the result of using map
, for
comprehension new map. there improve way start empty list , add together elements loop through (key, value) pairs in map
var mylist = list.empty[(double, string)] mymap foreach { case(k,v) => mylist ::= (v.somemember, k) }
use tolist
, map
.
for example:
scala> map("a" -> 1, "b" -> 2).tolist.map { case (k, v) => (k.size, v) } res12: list[(int, int)] = list((1,1), (1,2))
or, if want more memory efficient , not allocate intermediate list, can build list while map
ing breakout
import scala.collection.breakout scala> val l: list[(int, int)] = map("a" -> 1, "b" -> 2).map({ case (k, v) => (k.size, v) })(breakout) l: list[(int, int)] = list((1,1), (1,2))
scala
Comments
Post a Comment