Kotlin List reduceIndexed()
Syntax & Examples
Syntax of List.reduceIndexed()
The syntax of List.reduceIndexed() extension function is:
fun <S, T : S> Iterable<T>.reduceIndexed( operation: (index: Int, acc: S, T) -> S ): SThis reduceIndexed() extension function of List accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element with its index in the original collection.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining the integers[1, 2, 3, 4, 5]. - We use the
reduceIndexedfunction to accumulate values starting with the first element. - In the
operation,indexrepresents the index of the current element,accrepresents the accumulator value, andelementrepresents the current element. - We multiply the current element by its index and add it to the accumulator.
- Finally, we print the result to standard output using the
printlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val result = list.reduceIndexed { index, acc, element -> acc + index * element };
println(result);
}Output
41
2 Example
In this example,
- We create a list named
listcontaining the strings['apple', 'banana', 'cherry', 'date', 'elderberry']. - We use the
reduceIndexedfunction to accumulate values starting with the first element. - In the
operation,indexrepresents the index of the current element,accrepresents the accumulator value, andelementrepresents the current element. - We concatenate the current element with its index and add it to the accumulator.
- Finally, we print the result to standard output using the
printlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val result = list.reduceIndexed { index, acc, element -> acc + element + index };
println(result);
}Output
applebanana1cherry2date3elderberry4
Summary
In this Kotlin tutorial, we learned about reduceIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.