Kotlin
Summary - Advanced collections
Combine map, fold and groupBy to write a sales report.
Summary - Advanced collections
In this group you learned five core collection tools. map transforms, filter selects. fold reduces with an initial value, reduce starts from the first element. groupBy groups by key, partition splits in two.
sortedBy sorts by one field, sortedWith sorts many fields with a Comparator. associate produces a Map, flatMap flattens nested structures. Chain these tools to transform, select, merge and group data. Each function returns a new collection; the original stays unchanged.
Choosing the right tool
Pick the tool for the job: transform with map, select with filter, produce a single value with fold or reduce. Group with groupBy, split in two with partition, sort with sortedBy or sortedWith.
To produce a Map use associate, to open nested lists use flatMap. Chaining these functions builds a powerful data pipeline. Transform with map, narrow with filter, total with fold; or summarize per group with groupBy followed by mapValues.
Exercise Chain map, filter and fold
Define val numbers = listOf(1, 2, 3, 4, 5). Square each with map { it * it }, keep those greater than five with filter { it > 5 }, sum them with fold(0) { acc, n -> acc + n }. Print the result with println.
Show example solution
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.map { it * it }.filter { it > 5 }.fold(0) { acc, n -> acc + n }
println(result)
}
Exercise Summarize with groupBy and mapValues
Define data class Person(val name: String, val team: String). Create listOf(Person("Alex", "A"), Person("Sam", "B"), Person("Mara", "A")). Group by team with groupBy { it.team }, count members per team with mapValues { it.value.size } and print with println(counts).
Show example solution
data class Person(val name: String, val team: String)
fun main() {
val people = listOf(Person("Alex", "A"), Person("Sam", "B"), Person("Mara", "A"))
val counts = people.groupBy { it.team }.mapValues { it.value.size }
println(counts)
}
Test yourself
-
Which function transforms every element?
Show answer
map — map applies a transformation to each element.
-
Match the chain combinations
- map+filter+fold
- Transform-select-sum
- groupBy+mapValues
- Group-count
- sortedBy+forEach
- Sort-print
- partition+first
- Split-pick
Next lesson: by