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

前端 未结 6 2148
长发绾君心
长发绾君心 2020-12-05 22:43

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

6条回答
  •  天涯浪人
    2020-12-05 23:14

    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)
    

提交回复
热议问题