首页 文章

如何将Map的keySet与每个List Element合并:Scala

提问于
浏览
-1

我有一个像List这样的 Map 列表(map1,map2,map3)和另一个Map(String,String)说..在下面的例子中指定为外部的Map(String,String):

我希望名为“外部”的 Map 的键作为键,并将其映射到List中的m1 Map . 这意味着我想要在外部 Map 的键与列表中的 Map 之间进行一对一的映射

val m1 = Map("id"->"int", "firstname"->"String", "lastname"->"String")
val m2 = Map("Address"->"String", "Salary"->"Int")
val m3 = Map("Mobile" -> "Int", "email"->"String", "landline"->"int")

val listMap = List(m1,m2,m3)

val outer = Map("test1" -> "location_1", "test2" -> "location_2", "test3" -> "location_3")

val res = outer.map(out => listMap.map(inner => (out._1,inner)))

res.foreach(println)

这生成了输出:(我不想要)

List((test1,Map(id -> int, firstname -> String, lastname -> String)), (test1,Map(Address -> String, Salary -> Int)), (test1,Map(Mobile -> Int, email -> String, landline -> int)))
List((test2,Map(id -> int, firstname -> String, lastname -> String)), (test2,Map(Address -> String, Salary -> Int)), (test2,Map(Mobile -> Int, email -> String, landline -> int)))
List((test3,Map(id -> int, firstname -> String, lastname -> String)), (test3,Map(Address -> String, Salary -> Int)), (test3,Map(Mobile -> Int, email -> String, landline -> int)))
res0: Unit = ()

我想要的是:

Map(test1 -> map1, test2 -> map2, test3 -> map3)

我怎样才能做到这一点.. ??

2 回答

  • 0

    Map 不保留订单,所以我认为这不可能通过您的设置实现 . 这个怎么样?:

    val output: Map[String, Map[String, String]] = listMap.zipWithIndex
      .map { case (map, i) => s"test${i + 1}" -> map } (collection.breakOut)
    
  • 0

    我能够通过以下方式实现这一目标:

    val newMap = outer.zipWithIndex.map{
          x => (x._1._1, listMap.zipWithIndex.apply(x._2)._1)
        }
    
        newMap.map(println)
    

相关问题