只要設法提供另一個看似明確的方式,而不進口額外的類
val originalMap =
Map(
"uniquePersonId1" -> List("subaru", "honda"),
"uniquePersonId2" -> List("honda", "toyota")
)
// k1 -> List(A, B) change to List(A -> k1, B -> k1)
val intermediateList = originalMap.map {
case (key, strList) => strList.map(_ -> key)
}.toList.flatten
/*
intermediateList: List[(String, String)] = List((subaru,uniquePersonId1), (honda,uniquePersonId1), (honda,uniquePersonId2), (toyota,uniquePersonId2))
*/
val finalResult = intermediateList.foldLeft(Map[String, List[String]]())({
case (acc, (k1, v1)) => {
// if the key already exists, replace the value with new one
acc + {
k1 -> {
acc.find(_._1 == k1).map { matched =>
v1 :: matched._2
}.getOrElse {
(v1 :: Nil)
}
}
}
}
})
// Map(subaru -> List(uniquePersonId1), honda -> List(uniquePersonId2, uniquePersonId1), toyota -> List(uniquePersonId2))
println(finalResult)
太棒了!謝謝! – test123