1

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

4

2 回答 2

8

没有给定约束:

list.flatten
于 2012-07-27T15:04:04.243 回答
1

这有助于我了解 flatten 的工作原理。

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
}
于 2012-07-28T17:05:46.443 回答