Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Reduce

Reduce is an operation performed on collections to accumulate a single value out of it.

Sum is the simplest example of Reduce operation where we add up all the items in the collection to get a single value.

 // Syntax :
coll.reduce { acc, i -> /* return computed value */ }
 

For the first iteration, acc is taken as 0. If you want explicitly specify another value for initial acc, you can use fold() function :

 // Syntax :
coll.fold(/* initial acc */) { acc, i -> /* return computed value */ }
 

Example

Suppose we have a list of digits of a number and we need to compute the number using it i.e. we need to create a single Int from List<Int>. Example : [3, 4, 2, 1] → 3421

This is a perfect usecase for reduce operation. Algorithm :

 fun main() {
    val digits = listOf(3, 4, 2, 1)
    
    val num = digits.reduce { acc, i ->
        acc * 10 + i
    }
    println(num) // Prints 3421
}