title: flatten and flatMap in scala
body: <p>I'll like to check if I have understood flatten and flatMap functions correctly.</p>
  
  <p>1) Am I correct that flatten works only when a collection constitutes of other collections. Eg flatten would work on following lists</p>
  
  <pre><code>//list of lists
  val l1 = List(List(1,1,2,-1,3,1,-4,5), List("a","b"))
  
  //list of a set, list and map
  val l2 = List(Set(1,2,3), List(4,5,6), Map('a'-&gt;"x",'b'-&gt;"y"))
  </code></pre>
  
  <p>But flatten will not work on following</p>
  
  <pre><code>val l3 = List(1,2,3)
  val l4 = List(1,2,3,List('a','b'))
  val s1 = "hello world"
  val m1 = Map('h'-&gt;"h", 'e'-&gt;"e", 'l'-&gt;"l",'o'-&gt;"0")
  </code></pre>
  
  <p>'flatten' method would create a new list consisting of all elements by removing the hierarchy. Thus it sort of 'flattens' the collection and brings all elements at the same level.</p>
  
  <pre><code>l1.flatten
  res0: List[Any] = List(1, 1, 2, -1, 3, 1, -4, 5, a, b)
  
  l2.flatten
  res1: List[Any] = List(1, 2, 3, 1, 5, 6, (a,x), (b,y))
  </code></pre>
  
  <p>2) 'flatMap' first applies a method to elements of a list and then flattens the list.  As we noticed above, the flatten method works if lists have a hierarchy (contain other collections). Thus it is important that the method we apply to the elements returns a collection otherwise flatMap will not work</p>
  
  <pre><code>//we have list of lists
  val l1 = List(List(1,1,2,-1,3,1,-4,5), List("a","b"))
  
  l1 flatMap(x=&gt;x.toSet)
  res2: List[Any] = List(5, 1, -4, 2, 3, -1, a, b)
  
  val l2 = List(Set(1,2,3), List(1,5,6), Map('a'-&gt;"x",'b'-&gt;"y"))
  l2.flatMap(x=&gt;x.toSet)
  res3: List[Any] = List(1, 2, 3, 1, 5, 6, (a,x), (b,y))
  
  val s1 = "hello world"
  s1.flatMap(x=&gt;Map(x-&gt;x.toString)) 
  </code></pre>
  
  <p>We notice above that s1.flatten didn't work but s1.flatMap did. This is because, in s1.flatMap, we convert elements of a String (characters) into a Map which is a collection. Thus the string got converted into a collection of Maps like (Map('h'->"h"), Map('e'->"e"), Map('l'->"l"),Map ('l'->"l"),Map('o'->"o")....) Thus flatten will work now. Note that the Map created is not Map('h'->"h", 'e'->"e", 'l'->"l",....).</p>