
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin List - flatMap() Function
The Kotlin List 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 element of a list into an iterable such as a list and then flattens the result into a single 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 collection.
Syntax
Following is the syntax of Kotlin set flatMap() function −
list.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 List of List
Let's see a basic example of the flatMap() function, we can apply flatMap to list's elements −
fun main(args: Array<String>) { val nestedList = listOf( listOf(1, 2, 3), listOf(4, 5), listOf(6)) val flatList = nestedList.flatMap { it } println(flatList) }
Output
Following is the output −
[1, 2, 3, 4, 5, 6]
Example 2: Transforming and Flatting Strings.
In the following example, we use the toList and flatMap functions to transform elements into a list and then flatten the strings, respectively −
fun main(args: Array<String>) { val words = listOf("tutorialspoint", "India") val characters = words.flatMap { it.toList() } println(characters) }
Output
Following is the output −
[t, u, t, o, r, i, a, l, s, p, o, i, n, t, I, n, d, i, a]
Example 3: Flatten the Nested collection
Here, we create a list of sets. Then, we use theflatMap() function to flatten these sets into a single list of characters −
fun main(args: Array<String>) { val words = listOf( 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]