user3243499
user3243499

Reputation: 3151

How to convert a List of List to a List in Scala?

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

Answers (3)

pme
pme

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

Bogdan Vakulenko
Bogdan Vakulenko

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

Florian Baierl
Florian Baierl

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

Related Questions