Collections
Filter, map, group, partition, and chunk with functional operators.
Code
val nums = listOf(1, 2, 3, 4, 5, 6)
val mixed = mutableListOf("a", "b", "c")
// map / filter / reduce
val doubled = nums.map { it * 2 }
val evens = nums.filter { it % 2 == 0 }
val total = nums.reduce { acc, n -> acc + n }
println("$doubled $evens $total")
// groupBy and associateBy
data class Person(val name: String, val team: String)
val people = listOf(Person("A", "x"), Person("B", "y"), Person("C", "x"))
println(people.groupBy { it.team })
println(people.associateBy { it.name })
// flatMap and distinct
val nested = listOf(listOf(1, 2), listOf(3, 2), listOf(5))
println(nested.flatMap { it }.distinct().sorted())
// zip and partition
val keys = listOf("a", "b", "c")
val values = listOf(1, 2, 3)
println(keys.zip(values).toMap())
val (yes, no) = nums.partition { it > 3 }
println("yes=$yes no=$no")
// chunked and windowed
println((1..10).chunked(3))
println((1..5).windowed(2))
// Sequences for lazy pipelines
val sumSq = (1..1_000_000).asSequence()
.filter { it % 2 == 0 }
.map { it * it }
.take(5)
.toList()
println(sumSq)Explanation
Kotlin collections ship with functional operators like map, filter, groupBy, and partition that return new immutable lists. Sequences wrap collections for lazy, single-pass pipelines that avoid intermediate allocations. zip, chunked, and windowed handle pairing and sliding-window scenarios concisely.
More Kotlin Snippets
Null Safety
Use nullable types, safe calls, Elvis, and smart casts for null-safe code.
Data Classes
Model immutable data with auto-generated equals, copy, and destructuring.
Coroutines
Use launch, async, await, and structured concurrency with supervisorScope.
Extension Functions
Add methods to existing types with extensions and infix operators.
Sealed Classes
Model closed hierarchies and UI state with sealed classes and when.
When Expression
Branch on values, ranges, and types with when as statement or expression.