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
- map and flatMap: Transforming Every Element
- filter, filterNot, and partition
- fold, reduce, and runningFold
- Chaining Pipelines and Avoiding Intermediate Lists with Sequence