简体   繁体   中英

Scala flatten nested map

I have a nested Map like this one:

Map(1 -> Map(2 -> 3.0, 4 -> 5.0), 6 -> Map(7 -> 8.0))

I would like to 'flatten' it in a way such that the keys of the outer and inner maps are paired, ie for the example above:

Seq((1,2),(1,4),(6,7))

what is an elegant way to do this?

val m =  Map(1 -> Map(2 -> 3.0, 4 -> 5.0), 6 -> Map(7 -> 8.0))
m.toSeq.flatMap({case (k, v) => v.keys.map((k,_))})

With for-comprehension:

val m =  Map(1 -> Map(2 -> 3.0, 4 -> 5.0), 6 -> Map(7 -> 8.0))

scala> for((k1, v1) <- m.toSeq; k2 <- v1.keys) yield (k1, k2)
res4: Seq[(Int, Int)] = ArrayBuffer((1,2), (1,4), (6,7))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM