Part 06 / Topic 6 of 7
filter, map and sumOf: collections as ready-made tools
filter, map and sumOf each take a small lambda and do one specific, well-known job. For now, treat
them exactly like that — a tool you reach for, not something to take apart. Stage 2 Part 10 (Functional
Kotlin) is where lambdas, higher-order functions and sequences get a proper, in-depth treatment; this
section only covers the shape of each call and what it hands back.
val prices = listOf(68.0, 145.0, 52.0, 58.0, 45.0, 120.0)
// filter(predicate) keeps only the elements the lambda returns true for
val above100 = prices.filter { it > 100.0 }
println("Prices above ₹100: $above100")
// map(transform) produces a new list, same size, with every element transformed
val withGst = prices.map { it * 1.05 }
println("Prices with 5% GST: $withGst")
// sumOf(selector) adds up one number per element
val total = prices.sumOf { it }
println("Total: ₹$total")
Prices above ₹100: [145.0, 120.0]
Prices with 5% GST: [71.4, 152.25, 54.6, 60.900000000000006, 47.25, 126.0]
Total: ₹488.0
(The 60.900000000000006 is ordinary Double rounding from Part 2, not anything filter/map/sumOf
did — they pass the numbers through untouched.)
All three chain naturally, and all three work on a Map too, reading each entry through destructuring:
val totalAbove100 = prices.filter { it > 100.0 }.sumOf { it }
println("Total of prices above ₹100: ₹$totalAbove100")
val cart = mapOf("Rice (kg)" to 2, "Toor dal (kg)" to 1, "Milk (litre)" to 3)
val catalog = mapOf("Rice (kg)" to 68.0, "Toor dal (kg)" to 145.0, "Milk (litre)" to 58.0)
val cartTotal = cart.entries.sumOf { (item, qty) -> (catalog[item] ?: 0.0) * qty }
println("Cart total: ₹$cartTotal")
val bulkItems = cart.filter { (_, qty) -> qty >= 2 }
println("Items with quantity 2 or more: $bulkItems")
Total of prices above ₹100: ₹265.0
Cart total: ₹455.0
Items with quantity 2 or more: {Rice (kg)=2, Milk (litre)=3}
Full program: examples/06_filter_map_sumof.kt.
Done here? The practice set for Part 6 — including the solutions — is on the part page.