Flatmap vs Map in Kotlin

Flatmap vs Map in Kotlin

In this article, we are going to see the difference between flatmap and map in Kotlin via the sample code.

Let’s first create Data class in Kotlin having a list of items in the constructor:

data class Data(
    val items: List<String> = listOf()
)

Now, in the function main we are creating the list of Data class objects:

fun main() {
    val language = listOf(
        Data(
            listOf("Java", "Kotlin", "SpringBoot")
        ),
        Data(
            listOf("1", "2", "3")
        )
    )
    val mappedData = language.map { it.items }

    println("Mapping Data: $mappedData")
}

Let’s call flatMap and map on this data val and print the outputs:

fun main() {
    val language = listOf(
        Data(
            listOf("PHP", ".Net", "Angular")
        ),
        Data(
            listOf("10", "20", "30")
        )
    )

    val flatMapData = language.flatMap { it.items }

    println("Flattened Data: $flatMapData")
}

Read more