Kotlin Tutorials

Kotlin Set flatten()
Syntax & Examples

Set.flatten() extension function

The flatten() extension function in Kotlin returns a single list of all elements from all collections in the given set of collections.


Syntax of Set.flatten()

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.

Return Type

Set.flatten() returns value of type List.



✐ Examples

1 Flattening a set of lists

Using flatten() to flatten a set of lists into a single list.

For example,

  1. Create a set of lists of integers.
  2. Use flatten() to combine all the lists into a single list.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val setOfLists: Set<List<Int>> = setOf(listOf(1, 2), listOf(3, 4), listOf(5))
    val flatList = setOfLists.flatten()
    println(flatList)
}

Output

[1, 2, 3, 4, 5]

2 Flattening a set of sets

Using flatten() to flatten a set of sets into a single list.

For example,

  1. Create a set of sets of integers.
  2. Use flatten() to combine all the sets into a single list.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val setOfSets: Set<Set<Int>> = setOf(setOf(1, 2), setOf(3, 4), setOf(5))
    val flatList = setOfSets.flatten()
    println(flatList)
}

Output

[1, 2, 3, 4, 5]

3 Flattening a set of string lists

Using flatten() to flatten a set of lists of strings into a single list.

For example,

  1. Create a set of lists of strings.
  2. Use flatten() to combine all the lists into a single list.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val setOfStringLists: Set<List<String>> = setOf(listOf("one", "two"), listOf("three", "four"), listOf("five"))
    val flatList = setOfStringLists.flatten()
    println(flatList)
}

Output

[one, two, three, four, five]

Summary

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.