How to Reduce List in Kotlin: Simple Guide with Examples
In Kotlin, you can use the
reduce function to combine all elements of a list into a single value by applying an operation sequentially. The reduce function takes a lambda that specifies how to combine two elements at a time until one result remains.Syntax
The reduce function is called on a list and takes a lambda with two parameters: the accumulated value and the current element. It returns a single value after processing all elements.
- accumulator: holds the combined result so far.
- element: the current item from the list.
kotlin
val result = list.reduce { accumulator, element -> accumulator + element }Example
This example shows how to sum all numbers in a list using reduce. It starts with the first element and adds each next element to the accumulator.
kotlin
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, num -> acc + num }
println("Sum of numbers: $sum")
}Output
Sum of numbers: 15
Common Pitfalls
One common mistake is calling reduce on an empty list, which throws an exception because there is no initial value. Use reduceOrNull to safely handle empty lists.
Another pitfall is confusing reduce with fold. fold lets you provide an initial value, while reduce uses the first element as the initial accumulator.
kotlin
fun main() {
val emptyList = listOf<Int>()
// This will throw an exception:
// val result = emptyList.reduce { acc, num -> acc + num }
// Safe way:
val safeResult = emptyList.reduceOrNull { acc, num -> acc + num } ?: 0
println("Safe result for empty list: $safeResult")
}Output
Safe result for empty list: 0
Quick Reference
| Function | Description |
|---|---|
| reduce | Combines list elements using the first element as initial accumulator; throws on empty list. |
| reduceOrNull | Same as reduce but returns null on empty list instead of throwing. |
| fold | Combines list elements with a provided initial value; safe for empty lists. |
Key Takeaways
Use
reduce to combine list elements into one value by applying an operation sequentially.Avoid calling
reduce on empty lists to prevent exceptions; use reduceOrNull instead.fold is similar but requires an initial value and is safer for empty lists.reduce uses the first list element as the starting accumulator automatically.Always choose the right function based on whether your list might be empty.