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

我是研究僧i 提交于 2019-11-27 09:00:43

List has the flatten method. Why not use it?

List(List(1,2), List(3,4)).flatten
> List(1,2,3,4)

Given the above example, I'm not sure you need recursion. Looks like you want List.flatten instead.

e.g.

scala> List(1,2,3)
res0: List[Int] = List(1, 2, 3)

scala> List(4,5,6)
res1: List[Int] = List(4, 5, 6)

scala> List(res0,res1)
res2: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6)) 

scala> res2.flatten
res3: List[Int] = List(1, 2, 3, 4, 5, 6)

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

If your structure can be further nested, like:

List(List(1, 2, 3, 4, List(5, 6, List(7, 8))))

This function should give you the desire result:

def f[U](l: List[U]): List[U] = l match {
  case Nil => Nil
  case (x: List[U]) :: tail => f(x) ::: f(tail)
  case x :: tail => x :: f(tail)
}

You don't need recursion but you can use it if you want:

def flatten[A](list: List[List[A]]):List[A] = 
  if (list.length==0) List[A]() 
  else list.head ++ flatten(list.tail)

This works like flatten method build into List. Example:

scala> flatten(List(List(1,2), List(3,4)))
res0: List[Int] = List(1, 2, 3, 4)

If you want to use flatmap, here is the the way

Suppose that you have a List of List[Int] named ll, and you want to flat it to List, many people already gives you the answers, such as flatten, that's the easy way. I assume that you are asking for using flatmap method. If it is the case, here is the way

ll.flatMap(_.map(o=>o))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!