Reputation: 8494
I have a result of type List[List[Map[String,String]]]
and I would like to transform it into List[Map[String,String]]
. How would I do this in Scala?
Upvotes: 1
Views: 249
Reputation: 8064
This is helped me understand how flatten work.
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
}
Upvotes: 1