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:

class Data(val items: List<String>) {

}

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

fun main(args: Array<String>) {

val data = listOf(Data(listOf("a","b","c")),Data(listOf("1","2","3")))
}

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

fun main(args: Array<String>) {

val data = listOf(Data(listOf("a","b","c")),Data(listOf("1","2","3")))

val combined = data.flatMap { it.items }
println(combined)

val combinedMap = data.map { it.items }
println(combinedMap)

}

Output:

[a, b, c, 1, 2, 3]
[[a, b, c], [1, 2, 3]]

As per the above output, we can conclude:

flatMap merges the two collections into a single one.

Map simply results in a list of lists.