Kotlin List - flatMap() Function



The Kotlin List flatMap() function is particularly useful when working with nested collections or when we want to flatten the results of a transformation. This function transforms each element of a list into an iterable such as a list and then flattens the result into a single list.

Flatten is a collection function that takes a collection of collections, such as a list of the set, and combines all the collections into a single collection.

Syntax

Following is the syntax of Kotlin set flatMap() function −

list.flatMap { transformFunction(it) }

Parameters

This function takes a lambda function as a parameter to define the transformation logic for each element in the collection.

Return value

This function returns a List<R>, where R is the type of elements in the flattened collection.

Example 1: Flattening a List of List

Let's see a basic example of the flatMap() function, we can apply flatMap to list's elements −

fun main(args: Array<String>) {
   val nestedList = listOf(
      listOf(1, 2, 3),
      listOf(4, 5),
      listOf(6))
   val flatList = nestedList.flatMap { it }
   println(flatList)
}

Output

Following is the output −

[1, 2, 3, 4, 5, 6]

Example 2: Transforming and Flatting Strings.

In the following example, we use the toList and flatMap functions to transform elements into a list and then flatten the strings, respectively −

fun main(args: Array<String>) {
   val words = listOf("tutorialspoint", "India")
   val characters = words.flatMap { 
      it.toList()
   }
   println(characters)
}

Output

Following is the output −

[t, u, t, o, r, i, a, l, s, p, o, i, n, t, I, n, d, i, a]

Example 3: Flatten the Nested collection

Here, we create a list of sets. Then, we use theflatMap() function to flatten these sets into a single list of characters −

fun main(args: Array<String>) {
   val words = listOf(
      setOf('A', 'M', 'A', 'N'),
      setOf('K', 'U', 'M', 'A', 'R')
   )
   val result = words.flatMap {it}
   println(result)
}

Output

Following is the output −

[A, M, N, K, U, M, A, R]
kotlin_lists.htm
Advertisements