Kotlin Map - flatMap() Function



The Kotlin Map flatMap() function is particularly useful when working with nested collections or when we want to flatten the results of a transformation. This function transforms each entries of a map into an iterable such as a list and then flattens the resulting map into a single list.

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

Syntax

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

map.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 Map Values

Let's see a basic example of the flatMap() function, we can apply flatMap to its entries, key, or values −

fun main(args: Array<String>) {
   val map = mapOf("A" to listOf(1, 2), "B" to listOf(3, 4))
   val flatValues = map.flatMap { it.value }
   println(flatValues)
}

Output

Following is the output −

[1, 2, 3, 4]

Example 2: Transforming keys and values into a flat list.

In the following example, we can transform the map's key and value into a flat list by applying the flatMap() function −

fun main(args: Array<String>) {
   val map = mapOf("A" to 1, "B" to 2, "C" to 3)
   val flatMapResult =
      map.flatMap { (key, value) -> listOf("$key -> $value", "$key squared: ${value * value}") }
   println(flatMapResult)
}

Output

Following is the output −

[A -> 1, A squared: 1, B -> 2, B squared: 4, C -> 3, C squared: 9]

Example 3: Flatten the Nested Map

This is another example, we use a map where the value is also mapped and use the flatMap() function to flatten the inner maps into a list of strings representing key-values pair −

fun main(args: Array<String>) {
   val nestedMap = mapOf(
      "Group1" to mapOf("A" to 1, "B" to 2),
      "Group2" to mapOf("C" to 3, "D" to 4),
      "Group3" to mapOf("E" to 5, "F" to 6)
   )
   val flatResult = nestedMap.flatMap { (outerKey, innerMap) ->
      innerMap.map { (innerKey, value) ->
         "$outerKey-$innerKey: $value"
      }
   }
   println(flatResult)
}

Output

Following is the output −

[Group1-A: 1, Group1-B: 2, Group2-C: 3, Group2-D: 4, Group3-E: 5, Group3-F: 6]
kotlin_maps.htm
Advertisements