Home »
Scala
How to flatten a List of List in Scala?
By IncludeHelp Last updated : October 20, 2024
Flatten a List of List
Flattening of List is converting a list of multiple List into a single List. To flatten List of List in Scala we will use the flatten method.
Syntax
val newList = list.flatten
Program to flatten a list of list with numerical values
object MyClass {
def main(args: Array[String]) {
val ListofList = List(List(214, 56), List(6, 12, 34, 98))
println("List of List: " + ListofList)
println("Flattening List of List ")
val list = ListofList.flatten
println("Flattened List: " + list)
}
}
Output
List of List: List(List(214, 56), List(6, 12, 34, 98))
Flattening List of List
Flattened List: List(214, 56, 6, 12, 34, 98)
The same flatten method can also be applied to convert sequence of sequence to a single sequence(Array, list, Vector, etc.).
You can convert list of lists to list of type strings in two ways.
Method 1
object MyClass {
def main(args: Array[String]) {
val ListofList = List(List("Include", "Help"), List("Programming", "Tutorial"))
println("List of List: " + ListofList)
println("Flattening List of List ")
val list = ListofList.flatten
println("Flattened List: " + list)
}
}
Output
List of List: List(List(Include, Help), List(Programming, Tutorial))
Flattening List of List
Flattened List: List(Include, Help, Programming, Tutorial)
Method 2
Another way could split the list of list into character lists.
object MyClass {
def main(args: Array[String]) {
val ListofList = List("Include", "Help")
println("List of List: " + ListofList)
println("Flattening List of List ")
val list = ListofList.flatten
println("Flattened List: " + list)
}
}
Output
List of List: List(Include, Help)
Flattening List of List
Flattened List: List(I, n, c, l, u, d, e, H, e, l, p)