intermediate18 min

Collections: List, Map, and Functional Operations

Kotlin's List and Map, plus common functional operations like filter and map.

What you'll learn

  • Create a read-only List and a mutable MutableList
  • Create and read from a Map
  • Chain functional operations like filter and map over a collection

Explanation

Kotlin distinguishes read-only and mutable collection interfaces. listOf(1, 2, 3) creates a read-only List (no add/remove methods available); mutableListOf(1, 2, 3) creates a MutableList that supports them. This mirrors the val/var immutability preference at the collection-interface level -- prefer read-only collections unless mutation is genuinely needed.

A Map associates keys with values: mapOf("a" to 1, "b" to 2) creates a read-only map (note the to infix function building a key-value pair), read with map["a"] (returns the value or null if the key is missing, since Kotlin's map access is nullable-aware).

Kotlin collections support rich functional operations: filter keeps elements matching a condition, map transforms each element, and they chain naturally: listOf(1, 2, 3, 4).filter { it % 2 == 0 }.map { it * 10 } first keeps even numbers ([2, 4]) then multiplies each by 10 ([20, 40]).

Guided lab

Predict: Chaining filter and map over a list

KotlinNot executed
This lab does not run in your browser or on VisaSparkSchools's servers. Read the code, predict what it does, then reveal the real expected output.

Read this program and predict exactly what it prints.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val result = numbers.filter { it % 2 == 0 }.map { it * 10 }
    println(result)

    val ages = mapOf("Ada" to 30, "Grace" to 45)
    println(ages["Ada"])
    println(ages["Linus"])
}

Stuck? Get a hint.

Common mistakes

  • Trying to call add()/remove() on a List created with listOf(), forgetting it's read-only -- mutableListOf() is needed for that.
  • Assuming map["missingKey"] throws an exception -- it returns null instead, since Kotlin's map access is nullable-aware.
  • Chaining filter and map in the wrong order and getting a different (though sometimes still valid-looking) result than intended.

Knowledge check

Knowledge check

1. What does `listOf(1, 2, 3)` create?
2. What does `map["missingKey"]` return if the key isn't present?
3. What does `listOf(1, 2, 3, 4).filter { it % 2 == 0 }` produce?

Takeaway

Prefer read-only List/Map (listOf/mapOf) by default, and chain filter/map for concise, readable data transformations.

Summary

Kotlin distinguishes read-only from mutable collections; Map access is nullable-aware; filter and map chain to transform collections concisely.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.