Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Scala Programming: Flatten a given List of Lists, nested list structure

Scala Programming List Exercise-18 with Solution

Write a Scala program to flatten a given List of Lists, nested list structure.

Sample Solution:

Scala Code:

object Scala_List {    
   
  def flat_List(ls: List[_]): List[Any] = ls match {
  case Nil => Nil
  case (head: List[_]) :: tail => flat_List(head) ::: flat_List(tail)
  case head :: tail => head :: flat_List(tail)
   }  
  
  def main(args: Array[String]): Unit = {
     val all_lists1 = List(List(1,3,5,7), List(2,4,6,8), List(31,32,33,34))
     println("Original List:")  
     println(all_lists1)
     val flatten_list1 = flat_List(all_lists1)
     println("Flatten list:")
     println(flatten_list1)
     val all_lists2 = List(1, List(2, 3, 4), List(List(List(5, 6, 7))), List(8, 9), List(10), 11)
     println("Original List:")
     println(all_lists2)
     val flatten_lists2 = flat_List(all_lists2)
     println("Flatten list:")
     println(flatten_lists2)
    }
}

Sample Output:

Original List:
List(List(1, 3, 5, 7), List(2, 4, 6, 8), List(31, 32, 33, 34))
Flatten list:
List(1, 3, 5, 7, 2, 4, 6, 8, 31, 32, 33, 34)
Original List:
List(1, List(2, 3, 4), List(List(List(5, 6, 7))), List(8, 9), List(10), 11)
Flatten list:
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to check a given list is a palindrome or not.
Next: Write a Scala program to triplicate each element immediately next to the given list of integers.

What is the difficulty level of this exercise?