您可以通过在第一个 Map 上使用 mapValues 来获得所需的值的键的每个 List,然后在此 lis 上使用 flatMap获得所需的值。
这是一个示例,请注意getOrElse 方法,以确保我们始终获得一个值,即使该键不存在。
val myMap1 = Map(
"testKey1" -> List("testValue1", "testValue2", "testValue3"),
"testKey2" -> List("testValue4", "testValue5", "testValue6"),
"testKey3" -> List("testValue7", "testValue8", "testValue9"),
"testKey4" -> List("testValue10", "testValue11", "testValue12")
)
val myMap2 = Map(
"testValue1" -> List(1, 2, 3),
"testValue2" -> List(5),
"testValue5" -> List(4, 5, 6),
"testValue10" -> List(7, 8, 9)
)
val myMap3 = myMap1.mapValues {
valuesList => valuesList.flatMap {
valueKey => myMap2.getOrElse(valueKey, List.empty[Int])
}
}
// myMap3: Map[String, List[Int]] = Map(
// testKey1 -> List(1, 2, 3, 5),
// testKey2 -> List(4, 5, 6),
// testKey3 -> List(),
// testKey4 -> List(7, 8, 9)
// )
如果您需要删除具有空值的键,您可以进行过滤。
myMap3.filter { case (_, values) => values.nonEmpty }
编辑
如果我想创建这个 myMap3,其中的值将是 myMap2 的键和它们各自的值。
鉴于myMap1 的值是myMap2 的键 列表,我认为您真正想要的是Map[String, Map[String, List[A]]。
val myMap4 = myMap1.mapValues {
valuesList => valuesList.map {
valueKey => valueKey -> myMap2.getOrElse(valueKey, List.empty[Int])
}.toMap
}
// myMap4: Map[String, Map[String, List[Int]]] = Map(
// testKey1 -> Map(testValue1 -> List(1, 2, 3), testValue2 -> List(5), testValue3 -> List()),
// testKey2 -> Map(testValue4 -> List(), testValue5 -> List(4, 5, 6), testValue6 -> List()),
// testKey3 -> Map(testValue7 -> List(), testValue8 -> List(), testValue9 -> List()),
// testKey4 -> Map(testValue10 -> List(7, 8, 9), testValue11 -> List(), testValue12 -> List())
// )
同样,您可以过滤不需要的空值。
val myMap5 = myMap1.mapValues {
valuesList => valuesList.flatMap { // here we use flatMap, to filter any None.
valueKey => myMap2.get(valueKey).map(values => valueKey -> values)
}.toMap
} filter {
case (_, values) => values.nonEmpty
}
// myMap5: Map[String, Map[String, List[Int]]] = Map(
// testKey1 -> Map(testValue1 -> List(1, 2, 3), testValue2 -> List(5)),
// testKey2 -> Map(testValue5 -> List(4, 5, 6)),
// testKey4 -> Map(testValue10 -> List(7, 8, 9))
// )