The flatMap function

Another awesome function available with collections framework is the flatMap function.

Like the map function, it receives each of the items in the collection as an iteration, but, unlike the map function, it should return another collection for each of the items passed. These returned collections are then combined to create the resultant collection.

Have a look at the following example:

fun main(args: Array<String>) { 
    val list = listOf(10,20,30) 
 
    val flatMappedList = list.flatMap { 
        it.rangeTo(it+2).toList() 
    } 
 
    println("flatMappedList -> $flatMappedList") 
} 

The output looks like the following:

While the original list contained only three numbers—10, 20, and 30, the resultant list contains three more numbers for each of the numbers in the original list, all thanks to the flatMap function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.93.141