Collections & Functional Operations

Read-only and mutable collections, filter/map/groupBy/partition, and lazy sequences.

Kotlin's standard library has a rich, consistent set of collection operations. Read-only List, Set and Map are the default; mutable versions are explicit. Most data processing becomes a short chain of filter, map, groupBy and friends.

Analysing test results

listOf, mapOf, setOf create read-only collections; mutableListOf etc. mutable ones.

filter, map, sumOf, maxByOrNull, any answer questions in one line each.

groupBy builds a Map from key to list; destructuring (board, rs) iterates over it.

toSortedSet removes duplicates and sorts; owners["ota"] ?: "nobody" handles a missing key.

generateSequence(...).map.filter.take is lazy: only enough elements are computed to find three results.

partition splits into matching and non-matching lists; windowed(2) gives consecutive pairs.

val list = listOf(1, 2) list.add(3) // unresolved reference val list = mutableListOf(1, 2) list.add(3) listOf returns a read-only List interface without add; use a mutable list when you need to change it.

When should you use a Sequence instead of a List chain?

For long chains on large or infinite data where intermediate lists would be wasteful, or when you only need the first few results (take, first) — sequences evaluate lazily, element by element.