如何将List [List [Map [String,String]]]转换为List [Map [String,String]]

时间:2012-07-27 15:01:49

标签: scala

我的结果类型为List[List[Map[String,String]]],我想将其转换为List[Map[String,String]]。我将如何在Scala中执行此操作?

2 个答案:

答案 0 :(得分:8)

没有给出限制:

list.flatten

答案 1 :(得分:1)

这有助于我理解如何扁平化工作。

val a = List( List( Map( 11 -> 11 ), Map( 12 -> 12 ) ), List( Map( 21 -> 21 ), Map( 21 -> 21 ) ) )

def flatten(ls: List[Any]): List[Any] = ls flatMap {
    case ms: List[_] => flatten(ms)
    case e => List(e)
}

flatten( a )

/** Converts this $coll of traversable collections into
   *  a $coll in which all element collections are concatenated.
   *
   *  @tparam B the type of the elements of each traversable collection. 
   *  @param asTraversable an implicit conversion which asserts that the element
   *          type of this $coll is a `Traversable`.
   *  @return a new $coll resulting from concatenating all element ${coll}s.
   *  @usecase def flatten[B]: $Coll[B]
   */
def flatten[B](implicit asTraversable: A => /*<:<!!!*/ TraversableOnce[B]): CC[B] = {
    val b = genericBuilder[B] // incrementally build
    for (xs <- sequential)    // iterator for your collection
      b ++= asTraversable(xs) // am i traversable ?
    b.result                  // done ... build me
}