How to convert a list of String lists to a list of objects in Scala?

69 Views Asked by At

I'm reading a .csv file that returns a list of String lists, recipiesList, in the following format:

List(List(Portuguese Green Soup, Portugal), List(Grilled Sardines, Portugal), List(Salted Cod with Cream, Portugal))

I have a class Recipe, which has been defined in the following manner:

case class Recipe(name: String, country: String)

Is there any immediate way that I can transform recipiesList into a list of type List[Recipe]? Such as with map or some sort of extractor?

2

There are 2 best solutions below

5
Jesper On BEST ANSWER

You can transform elements of a List using the map method:

val input = List(List("Portuguese Green Soup", "Portugal"),
    List("Grilled Sardines", "Portugal"),
    List("Salted Cod with Cream", "Portugal"))

val output = input map { case List(name, country) => Recipe(name, country) }
0
Assaf Mendelson On

The quick way would be:

recipiesList.map(s => Recipe(s(0), s(1))