Thursday, 10 September 2020

Scala: Convert a map of (key, value) to map of (value, key)

We can do this easily using for loop with yield.

 

Example

val employeeIdsByName = for((id, name) <- employeeNamesById) yield (name, id)

scala> val employeeNamesById = Map(1 -> "Ram", 2 -> "Gopi", 3 -> "Joel")
val employeeNamesById: scala.collection.immutable.Map[Int,String] = Map(1 -> Ram, 2 -> Gopi, 3 -> Joel)

scala> val employeeIdsByName = for((id, name) <- employeeNamesById) yield (name, id)
val employeeIdsByName: scala.collection.immutable.Map[String,Int] = Map(Ram -> 1, Gopi -> 2, Joel -> 3)




Previous                                                    Next                                                    Home

No comments:

Post a Comment