如何从Scala嵌套Map中生成Seq内整数的所有组合?
Hey there! Let's figure out how to generate those triple combinations from your nested Map. The key here is using flatMap strategically to "flatten" each layer of nesting instead of keeping collections nested inside each other.
Let's break down the approach
Your structure is a Map[Int, Map[String, Seq[Int]]]—so we need to work through three layers:
- The outer map's keys (
Int) and their inner maps - Each inner map's keys (
String) and their sequences of integers - Each integer in the sequence, paired with the outer key and inner key
Here's the working code that will give you exactly the output you want:
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)) ) val result: List[(Int, String, Int)] = m.flatMap { case (outerNum, innerMap) => innerMap.flatMap { case (letter, nums) => nums.map(num => (outerNum, letter, num)) } }.toList
Why this works:
- Outer
flatMap: For each entry in the top-level map, we process its inner map and flatten the results into a single collection (instead of getting a collection of collections). - Inner
flatMap: For each entry in the inner map, we process its sequence of integers and flatten those into individual tuples (so we don't end up with sequences nested inside the result). - Innermost
map: Takes each integer in the sequence and pairs it with the outer number and inner string to create the desired triple. toList: Converts the final Map (sinceflatMapon a Map returns another Map) into a List to match your expected output format.
If you run this code, you'll get exactly the list of tuples you showed in your example!
Common mistake to avoid:
If you use map instead of flatMap at either layer, you'll end up with nested collections (like Map[Int, Map[String, Seq[(Int, String, Int)]]])—which is not what you want. flatMap is essential here to collapse those layers into a single flat sequence of tuples.
内容的提问来源于stack exchange,提问作者user3685285

