You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Scala嵌套Map中生成Seq内整数的所有组合?

解决嵌套Map的元素组合问题

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:

  1. The outer map's keys (Int) and their inner maps
  2. Each inner map's keys (String) and their sequences of integers
  3. 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 (since flatMap on 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:52:14