0Pricing
Kotlin Academy · Lesson

map and flatMap: Transforming Every Element

Transform collections with map and flatten nested results with flatMap.

Transformation Basics

map applies a function to each element, returning a new collection of the same size. flatMap does the same but flattens lists-of-lists into a single list.

Basic map

Transform each element with a lambda; the result has the same size as the input.

fun main() {
    val nums = listOf(1, 2, 3, 4)
    val squares = nums.map { it * it }
    println(squares) // [1, 4, 9, 16]
}

All lessons in this course

  1. map and flatMap: Transforming Every Element
  2. filter, filterNot, and partition
  3. fold, reduce, and runningFold
  4. Chaining Pipelines and Avoiding Intermediate Lists with Sequence
← Back to Kotlin Academy