Home » Scala language

How to flatten a List of List in Scala?

Scala | flatten a List of List: Here, we are going to learn how to flatten List of List in Scala using flatten method?
Submitted by Shivang Yadav, on April 17, 2020

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.

Let's explore how to?

Program:

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)

Another way could split the list of list into character lists.

Program:

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)



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.