Collections, Sequences and Functional Ops

Harry · 23 Sep 2026 · 3 views
Log in to track your progress and mark lessons complete.

Immutable First

val langs = listOf("Java", "Kotlin")   // read-only view
val scores = mutableListOf(10, 20)     // editable
val capitals = mapOf("IN" to "Delhi")

The Everyday Operators

val nums = (1..10).toList()
nums.filter { it % 2 == 0 }            // [2,4,6,8,10]
    .map { it * it }                   // [4,16,36,64,100]
    .sum()                             // 220
nums.any { it > 9 }                  // true
nums.firstOrNull { it > 100 }        // null, no crash
nums.groupBy { it % 2 == 0 }           // {false=[...], true=[...]}

Sequences for Big Pipelines

(1..1_000_000).asSequence()
    .filter { it % 2 == 0 }
    .map { it * 2 }
    .take(5).toList()                  // stops early - lazy

Lists process every step fully; sequences stream lazily and quit early. Use sequences for large or infinite data.

Destructuring and Zips

val (name, price) = "Clean Code" to 499
for ((i, book) in books.withIndex()) println("$i $book")

Collection pipeline filter map sum plus lazy sequences

Key Points

  • Default to immutable collections.
  • filter/map/firstOrNull cover most data tasks.
  • Sequences win on large or short-circuit pipelines.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in