Kotlin flatMap Function | Flatten and Transform Lists in Kotlin

The flatMap function in Kotlin is used to transform each element of a collection into an iterable (such as a list), and then flatten the resulting collections into a single list. This function is part of the Kotlin standard library and provides a convenient way to perform transformations that result in multiple elements for each input element and combine them into a single list.

Table of Contents

  1. Introduction
  2. flatMap Function Syntax
  3. Understanding flatMap
  4. Examples
    • Basic Usage
    • Flattening a List of Lists
    • Transforming and Flattening
  5. Real-World Use Case
  6. Conclusion

Introduction

The flatMap function allows you to transform each element of a collection into an iterable and then flatten the resulting iterables into a single list. This is useful for scenarios where each element of the original collection should produce multiple elements in the resulting collection.

flatMap Function Syntax

The syntax for the flatMap function is as follows:

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

Parameters:

  • transform: A lambda function that takes an element of the original collection as input and returns an iterable of transformed values.

Returns:

  • A new list containing the concatenated results of applying the transformation function to each element of the original collection.

Understanding flatMap

The flatMap function iterates over each element in the original collection, applies the given transformation function to it, and concatenates all the resulting iterables into a single list. This allows you to perform transformations that generate multiple elements for each input element and combine them into one list.

Examples

Basic Usage

To demonstrate the basic usage of flatMap, we will transform a list of strings into lists of characters and flatten the results into a single list.

Example

fun main() {
    val words = listOf("apple", "banana", "cherry")
    val characters = words.flatMap { it.toList() }
    println("Characters: $characters")
}

Output:

Characters: [a, p, p, l, e, b, a, n, a, n, a, c, h, e, r, r, y]

Flattening a List of Lists

This example shows how to use flatMap to flatten a list of lists.

Example

fun main() {
    val listOfLists = listOf(
        listOf(1, 2, 3),
        listOf(4, 5),
        listOf(6, 7, 8, 9)
    )
    val flattenedList = listOfLists.flatMap { it }
    println("Flattened list: $flattenedList")
}

Output:

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

Transforming and Flattening

This example demonstrates how to use flatMap to transform each element into a list of elements and flatten the results.

Example

data class Person(val name: String, val friends: List<String>)

fun main() {
    val people = listOf(
        Person("Alice", listOf("Bob", "Charlie")),
        Person("David", listOf("Eve", "Frank")),
        Person("Grace", listOf("Heidi"))
    )
    val allFriends = people.flatMap { it.friends }
    println("All friends: $allFriends")
}

Output:

All friends: [Bob, Charlie, Eve, Frank, Heidi]

Real-World Use Case

Transforming and Flattening a List of Orders with Items

In real-world applications, the flatMap function can be used to transform and flatten a list of orders, where each order contains multiple items, into a single list of all items.

Example

data class Order(val id: Int, val items: List<String>)

fun main() {
    val orders = listOf(
        Order(1, listOf("Apple", "Banana")),
        Order(2, listOf("Cherry", "Date")),
        Order(3, listOf("Elderberry", "Fig", "Grape"))
    )
    val allItems = orders.flatMap { it.items }
    println("All items: $allItems")
}

Output:

All items: [Apple, Banana, Cherry, Date, Elderberry, Fig, Grape]

Conclusion

The flatMap function in Kotlin is a powerful and convenient way to transform elements of a collection into iterables and flatten the results into a single list. It allows you to perform complex transformations and combine the results in one step, making it useful for various applications, including data processing, transformation, and extraction. 

By understanding and using the flatMap function, you can effectively manage and process collections in your Kotlin applications.

Comments