2

My goal is to use a Map (immutable) instead of class to represent my data in Scala. I'm simply transforming the data from one source file into another format and using a Map seems reasonable rather modeling a class to represent my data.

Example:

I have a list of lists for my raw data.

val x = List(List("a","b","c"), List("x","y","z")) // the values, order matters
val y = List("field1","field2","field3") // the keys, order matters

I want to apply the schema to the raw data and create a List of Maps. Order wont matter with Map.

val z = List(Map("field1" -> "a", "field2" -> "b", "field3" -> "c"), List("field1" -> "x", "field2" -> "y", "field3" -> "z"))

I have tried zip but thats not what i want

val z = x zip(y) toMap
  z: scala.collection.immutable.Map[List[String],String] = Map(List(a, b, c) -> field1, List(x, y, z) -> field2)

I keep getting stuck on how I would map over x with y and return a Map. Some direction would be greatly appreciated.

EDITED: This approach was inspired by this talk by Rich Hickey.

1 Answer 1

7

I think you are on the right track with zip, you just need to be applying it to each item in x via map instead of applying it one time to x itself. This is one solution, I'm sure there are others:

x.map(xs => y.zip(xs).toMap)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks this works, I'm still learning scala so I think I was missing something when I tried the map.

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.