Kotlin List runningReduce()
Syntax & Examples
Syntax of List.runningReduce()
The syntax of List.runningReduce() extension function is:
fun <S, T : S> Iterable<T>.runningReduce( operation: (acc: S, T) -> S ): List<S>This runningReduce() extension function of List returns a list containing successive accumulation values generated by applying operation from left to right to each element and current accumulator value that starts with the first element of this collection.
✐ Examples
1 Example
In this example,
- We create a list of integers named
listcontaining elements1, 2, 3, 4, 5. - We use the
runningReducefunction to apply addition from left to right starting with the first element of the list as the initial accumulator value. - The resulting list of accumulated values is stored in
result. - We print
resultusingprintln().
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val result = list.runningReduce { acc, element -> acc + element }
println(result)
}Output
[1, 3, 6, 10, 15]
2 Example
In this example,
- We create a list of strings named
listcontaining elements"apple", "banana", "cherry". - We use the
runningReducefunction to concatenate strings from left to right starting with the first string of the list as the initial accumulator value. - The resulting list of accumulated strings is stored in
result. - We print
resultusingprintln().
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val result = list.runningReduce { acc, element -> acc + element }
println(result)
}Output
[apple, applebanana, applebananacherry]
Summary
In this Kotlin tutorial, we learned about runningReduce() extension function of List: the syntax and few working examples with output and detailed explanation for each example.