The flatten() extension function in Kotlin returns a single list of all elements from all collections in the given set of collections.
The syntax of Set.flatten() extension function is:
fun <T> Set<Iterable<T>>.flatten(): List<T>
This flatten() extension function of Set returns a single list of all elements from all collections in the given collection.
Set.flatten() returns value of type List
.
Using flatten() 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.flatten()
println(flatList)
}
[1, 2, 3, 4, 5]
Using flatten() to flatten a set of sets into a single list.
For example,
fun main() {
val setOfSets: Set<Set<Int>> = setOf(setOf(1, 2), setOf(3, 4), setOf(5))
val flatList = setOfSets.flatten()
println(flatList)
}
[1, 2, 3, 4, 5]
Using flatten() to flatten a set of lists of strings into a single list.
For example,
fun main() {
val setOfStringLists: Set<List<String>> = setOf(listOf("one", "two"), listOf("three", "four"), listOf("five"))
val flatList = setOfStringLists.flatten()
println(flatList)
}
[one, two, three, four, five]
In this Kotlin tutorial, we learned about flatten() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.