Kotlin

map / filter / reduce

admin by @admin ADMIN
2h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
The three classic functional combinators. Each takes a lambda and returns a new collection (or a single value for reduce). Chain freely — intermediate allocations only matter at very large scale (use `Sequence` then).
Kotlin
Raw
fun main() {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    // filter — keep elements matching a predicate
    val evens = nums.filter { it % 2 == 0 }
    println(evens)                                  // [2, 4, 6, 8, 10]

    // map — transform each element
    val squares = nums.map { it * it }
    println(squares)                                // [1, 4, 9, ..., 100]

    // Chain — usually most readable
    val sumOfEvenSquares = nums
        .filter { it % 2 == 0 }
        .map    { it * it }
        .sum()
    println(sumOfEvenSquares)                       // 220

    // reduce — collapse to a single value (no initial value)
    val product = nums.reduce { acc, n -> acc * n }
    println(product)                                // 3628800

    // fold — like reduce but with an explicit initial value (handles empty lists)
    val concat = nums.fold("") { acc, n -> "$acc-$n" }
    println(concat)                                 // -1-2-3-4-5-...-10
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.