I am trying to convert a list to map in scala.
Input
val colNames = List("salary_new", "age_new", "loc_new")
Output
Map(salary_new -> salary, age_new -> age, loc_new -> loc)
Following code is working, but seems like I am over killing it.
val colRenameMap = colNames.flatMap(colname => Map(colname -> colname.split("_")(0))).toMap
flatMapwith amapand remove the creation of the inner Map.Mapand it didn't worked. Not able to understand why?mapis defined likedef map[A, B](fa: F[A])(f: A => B): F[B](F here is List, Map, Set, Vector, etc) so it takes a function and applies it to every element inside the collection. Whereasdef flatMap[A, B](fa: F[A])(f A => F[B]): F[B]so it is like map, but it is aware of the intermediate collections and flatten them. So, if you lave the inner Map you construct a list of maps, which is not what you want.toMapto this without usingflatMaptoMaptransforms a list of tuples into a map, not a list of maps into a map. So,list.map(Map)returns a list of maps,List.flatMap(Map)returns a list of tuples andlist.map(Tuple)also returns a list of tuples.