Reputation: 57
I have the following List[List[Any]]
which I want to convert to List[List[String]]
.
val input:List[List[Any]] = List(List(1234), List(234, 678), List(8765, 90876, 1))
I am looking for the following output:
val output:List[List[String]] = List(List(1234), List(234, 678), List(8765, 90876, 1))
I have tried doing the following:
val output:List[List[String]] = input.map(_.toString).toList
// or
val output:List[List[String]] = input.map(_.toString)
None of the above give me the desired output.
Upvotes: 1
Views: 786
Reputation: 3055
Because, your list is nested, you need to map it twice.
Why below is not working?
val output:List[List[String]] = input.map(_.toString)
Because, _ placeholder
holds value of type List[String]
and applying toString
method convert the List
to String
and hence result will be of type List[String]
instead of List[List[String]]
.
scala> input.map(_.toString)
res2: List[String] = List(List(1234), List(234, 678), List(8765, 90876, 1))
Therefore, you need to map input twice.
scala> input.map(_.map(_.toString))
res0: List[List[String]] = List(List(1234), List(234, 678), List(8765, 90876, 1))
Upvotes: 3