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?
-
1If you get this result from "map" method, just use "flatMap"viktortnk– viktortnk2012-07-27 16:52:32 +00:00Commented Jul 27, 2012 at 16:52
Add a comment
|
2 Answers
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
}
1 Comment
Debilski
This is not how the ‘real’
.flatten works, however: a) This will eliminate all nested Lists and not only one layer. b) You should do better than returning Any. c) Proper .flatten: ls flatMap { case x => x }