KtKotlin · Lesson 5 of 8

Collections & Lambdas

filter, map, sumOf, groupBy — Kotlin's collection pipeline turns loop-heavy code into declarative one-liners. This style dominates real Android codebases.

Kotlin
fun main() {
    // Read-only vs mutable is explicit:
    val nums = listOf(3, 1, 4, 1, 5, 9)        // List<Int>
    val mut = mutableListOf(1, 2)              // can add/remove
    mut.add(3)

    val ages = mapOf("Ada" to 17, "Alan" to 16)
    println(ages["Ada"])                        // 17
    val unique = setOf(1, 2, 2, 3)              // {1, 2, 3}

    // Lambdas: { parameters -> body }
    val double = { n: Int -> n * 2 }
    println(double(21))                         // 42
}
Kotlin
data class Student(val name: String, val grade: Int)

fun main() {
    val students = listOf(
        Student("Ada", 95),
        Student("Alan", 88),
        Student("Grace", 92),
        Student("Linus", 76),
    )

    // 'it' = the single lambda parameter:
    val honorRoll = students
        .filter { it.grade >= 90 }
        .map { it.name }
        .sorted()
    println(honorRoll)                    // [Ada, Grace]

    val avg = students.map { it.grade }.average()
    val best = students.maxByOrNull { it.grade }
    val byPass = students.groupBy { it.grade >= 80 }
    val total = students.sumOf { it.grade }

    students.forEach { println(it.name) }

    // first/any/all/none:
    students.any { it.grade == 100 }      // false
    students.all { it.grade >= 70 }       // true
}
✦ Tip
When a lambda is the last argument, it moves outside the parentheses — filter { ... } rather than filter({ ... }). That trailing-lambda rule is why Kotlin DSLs (Jetpack Compose, Gradle) look like built-in syntax.