Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 42 / 68

Flattening a List

In this lesson you will learn how to flatten a nested list with flatten in Kotlin, so a complex structure becomes simple to work with. This is for anyone searching for "Kotlin flatten how to use".

Expanding a list that contains other lists into one flat list is called flattening. In Kotlin .flatten() does it in one line.

The sample code runs nested.flatten() on the nested listOf(listOf(1, 2), listOf(3, 4), listOf(5)) and expands it into the single list [1, 2, 3, 4, 5]. It is a good illustration of how concise the Kotlin standard library is.

A common stumbling block for beginners is the difference from flatMap. flatten() flattens an already-nested list as it is, while flatMap is a separate method that transforms and flattens at the same time.

In real-world development it is a useful technique whenever you want to treat nested data as one list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)