The flatMapTo() extension function in Kotlin appends all elements yielded from the results of the transform function being invoked on each element of the original set to the given destination collection.
The syntax of Set.flatMapTo() extension function is:
fun <T, R, C : MutableCollection<in R>> Set<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C
This flatMapTo() extension function of Set appends all elements yielded from results of transform function being invoked on each element of original collection, to the given destination.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which the resulting elements will be appended. |
transform | required | A function that takes an element and returns an iterable of results. |
Set.flatMapTo() returns value of type C
.
Using flatMapTo() to append the results of flattening a set of lists into a single list to a destination list.
For example,
fun main() {
val setOfLists: Set<List<Int>> = setOf(listOf(1, 2), listOf(3, 4), listOf(5))
val destinationList = mutableListOf<Int>()
setOfLists.flatMapTo(destinationList) { it }
println(destinationList)
}
[1, 2, 3, 4, 5]
Using flatMapTo() to append the results of flattening a set of strings into a single list of characters to a destination set.
For example,
fun main() {
val setOfStrings: Set<String> = setOf("one", "two", "three")
val destinationSet = mutableSetOf<Char>()
setOfStrings.flatMapTo(destinationSet) { it.toList() }
println(destinationSet)
}
[o, n, e, t, w, h, r]
Using flatMapTo() to append the results of flattening a set of integers into a single list of their factors to a destination list.
For example,
fun main() {
val setOfIntegers: Set<Int> = setOf(6, 8)
val destinationList = mutableListOf<Int>()
setOfIntegers.flatMapTo(destinationList) { number -> (1..number).filter { number % it == 0 } }
println(destinationList)
}
[1, 2, 3, 6, 1, 2, 4, 8]
In this Kotlin tutorial, we learned about flatMapTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.