Kotlin Array.flatMap()

Kotlin Array.flatMap() Tutorial

In Kotlin, the Array.flatMap() function is used to transform each element of the array into a collection of elements and then flatten the result into a single list.

This tutorial will explore the syntax of the flatMap() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the flatMap() function is as follows:

inline fun <T, R> Array<out T>.flatMap(
    transform: (T) -> Iterable<R>
): List<R>

where

ParameterDescription
transformFunction that is invoked on each element of the array.
Parameters of Array.flatMap()

Examples for Array.flatMap() function

1. Using flatMap() to Flatten Nested Arrays

In this example, we’ll use the flatMap() function to flatten a nested array of integers into a single list.

Kotlin Program

fun main() {
    val nestedArray = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6), arrayOf(7, 8, 9))

    // Using flatMap() to flatten the nested array
    val flatList = nestedArray.flatMap { it.toList() }

    // Printing the original nested array and the flattened list
    println("Nested Array:\n[${nestedArray.map { it.joinToString(", ", prefix = "[", postfix = "]") }.joinToString("\n")}]\n")
    println("Flattened List:\n$flatList")
}

Output

Nested Array:
[[1, 2, 3]
[4, 5, 6]
[7, 8, 9]]

Flattened List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

2. Using flatMap() with Strings

In this example, we’ll use the flatMap() function to transform each character of a string array into individual strings and then flatten the result.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "orange")

    // Using flatMap() to transform characters into individual strings and flatten the result
    val flattenedChars = wordsArray.flatMap { it.toCharArray().map { char -> char.toString() } }

    // Printing the original nested array and the flattened list
    println("Words Array:\n${wordsArray.contentToString()}\n")
    println("Flattened Chars:\n$flattenedChars")
}

Output

Words Array:
[apple, banana, orange]

Flattened Chars:
[a, p, p, l, e, b, a, n, a, n, a, o, r, a, n, g, e]

Summary

In this tutorial, we’ve covered the flatMap() function in Kotlin arrays, its syntax, and how to use it to transform and flatten arrays. This function is particularly useful for working with nested collections and converting elements into multiple values. Experiment with different transformations to suit your specific use case.