⚡ Kotlin Fundamentals
Collections & Higher-Order Functions
Lists, Maps, filter, map, reduce, flatMap, and sequences.

Core Collection Types

kotlin
// Immutable (read-only)
val fruits = listOf("Apple", "Banana", "Cherry")
val scores = mapOf("Alice" to 92, "Bob" to 87)

// Mutable
val tasks = mutableListOf("Buy groceries")
tasks.add("Walk dog")

val alice = scores["Alice"] ?: 0   // safe map access

Higher-Order Functions

kotlin
val numbers = (1..10).toList()

numbers.filter { it % 2 == 0 }        // [2,4,6,8,10]
numbers.map { it * it }               // [1,4,9,16,25...]
numbers.reduce { acc, n -> acc + n }   // 55
numbers.groupBy { if (it%2==0) "even" else "odd" }
numbers.sortedByDescending { it }
numbers.take(3)                        // [1,2,3]
numbers.sumOf { it.toDouble() }        // 55.0

Sequences — Lazy Evaluation

kotlin
// Process 1 million items without intermediate lists
val result = (1..1_000_000)
    .asSequence()
    .filter { it % 3 == 0 }
    .map { it * 2 }
    .take(10)
    .toList()   // only processes what's needed

Key Takeaways

Prefer immutable listOf/mapOf; use mutableListOf when needed
filter, map, reduce, groupBy, and flatMap cover most transformations
Sequences are lazy — chain operations without creating intermediate lists
sortedBy, take, drop, and sumOf handle common list operations elegantly
Lesson 9 of 30Kotlin Fundamentals
← Previous Next Lesson →