在Scala中将Map[String,List[String]]展开为笛卡尔乘积



我正在寻找Scala中基于映射类型将集[Set[String]]扩展为笛卡尔乘积的版本:

我想从开始

val values = Map(
"id" -> List("Paul","Joe"),
"number" -> List("1","2","3"),
"Type" -> List("A","B","C")
)

计算:

val final = Set(
Map("id" -> "Paul", "number" -> "1", "Type" -> "A" ),
Map("id" -> "Paul", "number" -> "1", "Type" -> "B" ),
Map("id" -> "Paul", "number" -> "1", "Type" -> "C" ),
Map("id" -> "Paul", "number" -> "1", "Type" -> "A" ),
Map("id" -> "Paul", "number" -> "1", "Type" -> "B" ),
Map("id" -> "Paul", "number" -> "1", "Type" -> "C" ),
Map("id" -> "Paul", "number" -> "2", "Type" -> "A" ),
Map("id" -> "Paul", "number" -> "2", "Type" -> "B" ),
Map("id" -> "Paul", "number" -> "2", "Type" -> "C" ),
....
Map("id" -> "Joe", "number" -> "3", "Type" -> "B" ),
Map("id" -> "Joe", "number" -> "3", "Type" -> "C" )
)

我尝试转换以下代码

def combine[A](xs: Traversable[Traversable[A]]): Seq[Seq[A]] =
xs.foldLeft(Seq(Seq.empty[A])){
(x, y) => for (a <- x.view; b <- y) yield a :+ b }

但我有一些问题需要理解如何构建所有要添加到大集合((中的映射

您可以这样做:
(但请注意,对于较大的映射,这将消耗大量内存,因此可能值得考虑生成LazyList(

def cartesianProductMap[A, B](data: Map[A, List[B]]): List[Map[A, B]] =
data.foldLeft(Map.empty[A, B] :: Nil) {
case (acc, (key, values)) =>
values.flatMap { b =>
acc.map(_ + (key -> b))
}
}

运行在Scastie中的代码。


BTW,如果您使用,您可以执行:values.to(SortedMap).sequence

相关内容

  • 没有找到相关文章

最新更新