Alex Rivera | Logout

Scala - convert List of Lists into a single List: List[List[A]] to List[A]

Asked 2012-09-26T11:38:08.153
42

What's the best way to convert a List of Lists in scala (2.9)?

I have a list:

List[List[A]]

which I want to convert into

List[A]

How can that be achieved recursively? Or is there any other better way?

Edit
Report

1 Answer

13

.flatten is obviously the easiest way, but for completeness you should also know about flatMap

 val l = List(List(1, 2), List(3, 4))
 println(l.flatMap(identity))

and the for-comprehension equivalent

 println(for (list <- l; x <- list) yield x)

flatten is obviously a special case of flatMap, which can do so much more.

answered 2012-09-26T13:36:57.563

Your Answer