Write a Scala program to flatten a given List of Lists, nested list structure.
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)
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer