map, filter, reduce
In this page:
Transforming with map
.map { } applies a transformation to every element of a collection and returns a brand-new list with the results, leaving the original collection untouched.
Example: Transforming with map
fun main() {
val numbers = listOf(1, 2, 3, 4)
val squares = numbers.map { it * it }
println(squares)
}
Login to try C/C++/Java/PHP code in the editor
Selecting with filter
.filter { } returns a new list containing only the elements for which the given predicate returns true, discarding the rest.
Example: Selecting with filter
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evens = numbers.filter { it % 2 == 0 }
println(evens)
}
Login to try C/C++/Java/PHP code in the editor
Combining into One Value with reduce
.reduce { acc, item -> ... } repeatedly combines elements into a single accumulated result, starting with the first element as the initial accumulator value.
Example: Combining into One Value with reduce
fun main() {
val numbers = listOf(1, 2, 3, 4)
val sum = numbers.reduce { acc, n -> acc + n }
println("Sum via reduce: $sum")
}
Login to try C/C++/Java/PHP code in the editor
Combining with fold and an Initial Value
.fold(initial) { acc, item -> ... } behaves like reduce but starts from an explicit initial value, which also makes it safe to use on an empty collection.
Example: Combining with fold and an Initial Value
fun main() {
val numbers = listOf<Int>()
val sum = numbers.fold(0) { acc, n -> acc + n }
println("Sum via fold on empty list: $sum")
val words = listOf("Kotlin", "is", "fun")
val sentence = words.fold("Result:") { acc, word -> "$acc $word" }
println(sentence)
}
Login to try C/C++/Java/PHP code in the editor
- Confusing
.reduce { }with.fold(initial) { };reduceuses the first element as the starting accumulator and throws on an empty collection, whilefoldtakes an explicit initial value. - Chaining
.filter { }.map { }in the wrong order and getting different (though sometimes equally valid) results than intended. - Forgetting these functions return a new collection or value and never mutate the original collection.
.map { transform }returns a new list with each element transformed according to the given function..filter { predicate }returns a new list containing only the elements that satisfy the given condition..reduce { acc, item -> ... }combines all elements into a single result, using the first element as the initial accumulator..fold(initial) { acc, item -> ... }is likereducebut takes an explicit starting value, so it also works on empty collections.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: