0

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
5
  • 1
    Well, you can change the flatMap with a map and remove the creation of the inner Map. Commented May 23, 2020 at 4:07
  • That worked. I was trying to do the same thing, but I had Map and it didn't worked. Not able to understand why? Commented May 23, 2020 at 4:11
  • map is defined like def 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. Whereas def 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. Commented May 23, 2020 at 4:21
  • I mean this one ` colNames.map(colname => Map(colname -> colname.split("_")(0)))` I was not able to apply toMap to this without using flatMap Commented May 23, 2020 at 4:29
  • 1
    Yes, it won't work. toMap transforms 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 and list.map(Tuple) also returns a list of tuples. Commented May 23, 2020 at 4:38

1 Answer 1

1

I think map instead of flatMap would be more suitable for your case. Also you don't need to use the Map type internally, a single tuple should do the job.

For the sake of completeness this is how the definition of toMap looks like:

toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U]

as you can see the method expects a (T, U) which is a Tuple2.

Finally, two options using map:

// option 1: key/value
colNames.map{c => c -> c.split("_")(0)}.toMap

// option 2: tuple
colNames.map{c => (c, c.split("_")(0))}.toMap
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.