Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 441
A Far Avatar asked Sep 26 '12 11:09

A Far


2 Answers

List has the flatten method. Why not use it?

List(List(1,2), List(3,4)).flatten > List(1,2,3,4) 
like image 104
Jan Avatar answered Oct 04 '22 07:10

Jan


.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.

like image 35
Dave Griffith Avatar answered Oct 04 '22 05:10

Dave Griffith