我有一个像这样的嵌套地图:
val m: Map[Int, Map[String, Seq[Int]]] =
Map(
1 -> Map(
"A" -> Seq(1, 2, 3),
"B" -> Seq(4, 5, 6)
),
2 -> Map(
"C" -> Seq(7, 8, 9),
"D" -> Seq(10, 11, 12),
"E" -> Seq(13, 14, 15)
),
3 -> Map(
"F" -> Seq(16, 17, 18)
)
)
我希望所需的输出显示Seqs中整数的每种可能组合。例如:
List((1, "A", 1),
(1, "A", 2),
(1, "A", 3),
(1, "B", 4),
(1, "B", 5),
(1, "B", 6),
(2, "C", 7),
(2, "C", 8),
(2, "C", 9),
(2, "D", 10),
(2, "D", 11),
(2, "D", 12),
(2, "E", 13),
(2, "E", 14),
(2, "E", 15),
(3, "F", 16),
(3, "F", 17),
(3, "F", 18))
我一直在尝试使用map和flatMap的不同组合,但没有任何工作。有什么想法吗?
答案 0 :(得分:7)
这是使用for comprehension的可能性:
for {
(k1, v1) <- m
(k2, v2) <- v1
v3 <- v2
} yield (k1, k2, v3)
这遍历m的所有顶部键/值对。对于每个这些最高值,这将遍历所有嵌套键/值。最后,对于所有这些嵌套值(列表),它会遍历每个元素并产生所请求的内容。
for comprehension相当于嵌套的flatMap
,例如:
m.flatMap{
case (k1, v1) => v1.flatMap {
case (k2, v2) => v2.map(v3 => (k1, k2, v3))
}
}