Reputation: 3151
I have a list of list as follows:
val xl = (0 until 5).map(i => {Seq(s"$i", s"Mr._$i")}).toList
I want to convert it to a list or Seq of strings as:
List("0", "Mr._0","1", "Mr._1","2", "Mr._2","3", "Mr._3","4", "Mr._4")
I am new to Scala and not able to find any functions in Scala which would help me convert the List of list to a List.
Upvotes: 1
Views: 791
Reputation: 14803
If there is a flatMap
involved for-comprehension
is always an elegant way:
for{
i <- 0 until 5
r <- Seq(s"$i", s"Mr._$i")
} yield r
Upvotes: 2
Reputation: 3390
Just use flatMap instead of map:
val xl = (0 until 5).flatMap(i => Seq(s"$i", s"Mr._$i"))
or
val xl = (0 until 5).map(i => Seq(s"$i", s"Mr._$i")).flatten
Upvotes: 4
Reputation: 2481
This works for me:
val xl = (0 until 5).map(i => List(s"$i", s"Mr._$i")).toList
println(xl.flatten)
Output: List(0, Mr._0, 1, Mr._1, 2, Mr._2, 3, Mr._3, 4, Mr._4)
Upvotes: 0