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