Kotlin Set - flatMap() Function



The Kotlin Set flatMap() function works seamlessly as a set collection just like it does with a list. This is useful for handling nested collections and flattening transformation results.

This function transforms each element of a set into an iterable like a list or another set and then flattens all the resulting collection into a list.

Flatten is a collection function that takes a collection of collections, such as a list of the set and combines all the collections into a single flat list.

Syntax

Following is the syntax of Kotlin set flatMap() function −

set.flatMap { transformFunction(it) }

Parameters

This function takes a lambda function as a parameter to define the transformation logic for each element in the collection.

Return value

This function returns a List<R>, where R is the type of elements in the flattened collection.

Example 1: Flattening a Set of List

Let's see a basic example of the flatMap() function, we can apply flatMap to set's elements −

fun main(args: Array<String>) {
   val nestedCollection = setOf(
      listOf(1, 2, 3),
      listOf(3, 4),
      listOf(4, 5)
   )
   val flatSet = nestedCollection .flatMap { it }
   println(flatSet)
}

Output

Following is the output −

[1, 2, 3, 3, 4, 4, 5]

Example 2: Transforming and Flatting Strings

In the following example, we use the toSet and flatMap functions to transform elements into a set and then flatten the strings, respectively −

fun main(args: Array<String>) {
   val string = setOf("tutorialspoint", "India")
   val characters = string .flatMap { 
      it.toSet()
   }
   println(characters)
}

Output

Following is the output −

[t, u, o, r, i, a, l, s, p, n, I, n, d, i, a]

Example 3: Flatten the Nested Set

Here, we create a set of sets. Then, we use theflatMap() function to flatten these sets into a single list of characters −

fun main(args: Array<String>) {
   val words = setOf(
      setOf('A', 'M', 'A', 'N'),
      setOf('K', 'U', 'M', 'A', 'R')
   )
   val result = words.flatMap {it}
   println(result)
}

Output

Following is the output −

[A, M, N, K, U, M, A, R]
kotlin_sets.htm
Advertisements