1

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?

1
  • 1
    If you get this result from "map" method, just use "flatMap" Commented Jul 27, 2012 at 16:52

2 Answers 2

8

No constraint given:

list.flatten
Sign up to request clarification or add additional context in comments.

Comments

1

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

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 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.