Standard Library Utilities
Collection Helpers
Use collection helpers to transform and summarize a short list.
collection-helpers
Small helpers such as `map`, `filter`, and `joinToString` make collection steps readable.
Collection Helpers
CollectionHelpers.kt
Replay: real traced execution (multi-file project)
fun main() {
val bonus = 2
val scores = listOf(1, 3, 5)
val adjusted = scores.map { score ->
score + bonus
}
val high = adjusted.filter { score ->
score >= 5
}
val summary = high.joinToString("-")
println("bonus=$bonus")
println("count=${high.size}")
println("summary=$summary")
}
fun main() {
val bonus = 0
val scores = listOf(1, 3, 5)
val adjusted = scores.map { score ->
score + bonus
}
val high = adjusted.filter { score ->
score >= 5
}
val summary = high.joinToString("-")
println("bonus=$bonus")
println("count=${high.size}")
println("summary=$summary")
}
fun main() {
val bonus = 5
val scores = listOf(1, 3, 5)
val adjusted = scores.map { score ->
score + bonus
}
val high = adjusted.filter { score ->
score >= 5
}
val summary = high.joinToString("-")
println("bonus=$bonus")
println("count=${high.size}")
println("summary=$summary")
}
bonus ← 2, scores ← [1, 3, 5], adjusted ← [3, 5, 7], high ← [5, 7]
1fun main() {2 val bonus→ 2 = 2 //@bonus=0, 53 val scores→ [1, 3, 5] = listOf(1, 3, 5)4 val adjusted→ [3, 5, 7] = scores[1, 3, 5].map { score ->5 score + bonus6 }7 val high→ [5, 7] = adjusted[3, 5, 7].filter { score ->8 score >= 59 }10 val summary→ 5-7 = high[5, 7].joinToString("-")1112 println("bonus=$bonus2")13 println("count=${high.size2}")14 println("summary=$summary5-7")15}outputbonus=2 count=2 summary=5-7
bonus ← 0, scores ← [1, 3, 5], adjusted ← [1, 3, 5], high ← [5]
1fun main() {2 val bonus→ 0 = 03 val scores→ [1, 3, 5] = listOf(1, 3, 5)4 val adjusted→ [1, 3, 5] = scores[1, 3, 5].map { score ->5 score + bonus6 }7 val high→ [5] = adjusted[1, 3, 5].filter { score ->8 score >= 59 }10 val summary→ 5 = high[5].joinToString("-")1112 println("bonus=$bonus0")13 println("count=${high.size1}")14 println("summary=$summary5")15}outputbonus=0 count=1 summary=5
bonus ← 5, scores ← [1, 3, 5], adjusted ← [6, 8, 10], high ← [6, 8, 10]
1fun main() {2 val bonus→ 5 = 53 val scores→ [1, 3, 5] = listOf(1, 3, 5)4 val adjusted→ [6, 8, 10] = scores[1, 3, 5].map { score ->5 score + bonus6 }7 val high→ [6, 8, 10] = adjusted[6, 8, 10].filter { score ->8 score >= 59 }10 val summary→ 6-8-10 = high[6, 8, 10].joinToString("-")1112 println("bonus=$bonus5")13 println("count=${high.size3}")14 println("summary=$summary6-8-10")15}outputbonus=5 count=3 summary=6-8-10