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

前端 未结 6 2138
长发绾君心
长发绾君心 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:10

    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)
    }
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-05 23:14

    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)
    
    0 讨论(0)
  • 2020-12-05 23:20

    List has the flatten method. Why not use it?

    List(List(1,2), List(3,4)).flatten
    > List(1,2,3,4)
    
    0 讨论(0)
  • 2020-12-05 23:21

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

    0 讨论(0)
  • 2020-12-05 23:27

    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))
    
    0 讨论(0)
提交回复
热议问题