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

时间:2017-11-20 00:32:17

标签: scala functional-programming

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

我想要名为'外部'的地图的键。作为键并将其映射到List中的m1映射。这意味着我希望外部地图的键与列表中的地图之间的一对一映射

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 :(得分:0)

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

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

答案 1 :(得分:0)

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

$sql = "
SELECT * FROM life
UNION
SELECT * FROM nature
UNION
SELECT * FROM beauty
ORDER BY RAND()
LIMIT 1
";