The flatMapTo 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 collection, storing the results in a specified destination collection. This function is part of the Kotlin standard library and provides a flexible way to apply transformations and collect the results in a custom collection.
Table of Contents
- Introduction
flatMapToFunction Syntax- Understanding
flatMapTo - Examples
- Basic Usage
- Flattening a List of Lists to a Mutable List
- Transforming and Flattening to a Mutable Set
- Real-World Use Case
- Conclusion
Introduction
The flatMapTo function allows you to transform each element of a collection into an iterable and then flatten the resulting iterables into a single collection, storing the results in a specified destination collection. This is useful for scenarios where each element of the original collection should produce multiple elements in the resulting collection, and you want to collect the results in a custom collection.
flatMapTo Function Syntax
The syntax for the flatMapTo function is as follows:
fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C
Parameters:
destination: The collection where the transformed and flattened elements will be stored.transform: A lambda function that takes an element of the original collection as input and returns an iterable of transformed values.
Returns:
- The destination collection containing the transformed and flattened elements.
Understanding flatMapTo
The flatMapTo function iterates over each element in the original collection, applies the given transformation function to it, and adds all the resulting elements to the specified destination collection. This allows you to perform transformations that generate multiple elements for each input element and collect the results in a custom collection in one step.
Examples
Basic Usage
To demonstrate the basic usage of flatMapTo, we will transform a list of strings into lists of characters and flatten the results into a single mutable list.
Example
fun main() {
val words = listOf("apple", "banana", "cherry")
val characters = mutableListOf<Char>()
words.flatMapTo(characters) { 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 to a Mutable List
This example shows how to use flatMapTo to flatten a list of lists into a single mutable list.
Example
fun main() {
val listOfLists = listOf(
listOf(1, 2, 3),
listOf(4, 5),
listOf(6, 7, 8, 9)
)
val flattenedList = mutableListOf<Int>()
listOfLists.flatMapTo(flattenedList) { it }
println("Flattened list: $flattenedList")
}
Output:
Flattened list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Transforming and Flattening to a Mutable Set
This example demonstrates how to use flatMapTo to transform elements and store the results in a mutable set, ensuring unique elements.
Example
fun main() {
val numbers = listOf("1", "2", "2", "3", "four", "4")
val validNumbers = mutableSetOf<Int>()
numbers.flatMapTo(validNumbers) { it.toIntOrNull()?.let { listOf(it) } ?: emptyList() }
println("Valid numbers: $validNumbers")
}
Output:
Valid numbers: [1, 2, 3, 4]
Real-World Use Case
Transforming and Flattening a List of Orders with Items to a Custom Collection
In real-world applications, the flatMapTo function can be used to transform and flatten a list of orders, where each order contains multiple items, into a single custom collection 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 = mutableListOf<String>()
orders.flatMapTo(allItems) { it.items }
println("All items: $allItems")
}
Output:
All items: [Apple, Banana, Cherry, Date, Elderberry, Fig, Grape]
Conclusion
The flatMapTo function in Kotlin is a powerful and flexible way to transform elements of a collection into iterables and flatten the results into a single destination collection. 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 flatMapTo function, you can effectively manage and process collections in your Kotlin applications.