Kotlin List reduce()
Syntax & Examples


Syntax of List.reduce()

The syntax of List.reduce() extension function is:

fun <S, T : S> Iterable<T>.reduce( operation: (acc: S, T) -> S ): S

This reduce() 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.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the reduce function to accumulate the elements by adding them together from left to right.
  • The final accumulated value, which is the sum of all elements, is stored in sum.
  • We print sum using println().

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val sum = list.reduce { acc, element -> acc + element }
    println(sum)
}

Output

15

2 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry", "date", "elderberry".
  • We use the reduce function to accumulate the strings by concatenating them with commas from left to right.
  • The final accumulated value, which is the concatenated string of all elements separated by commas, is stored in concatenatedString.
  • We print concatenatedString using println().

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry", "date", "elderberry")
    val concatenatedString = list.reduce { acc, element -> "$acc, $element" }
    println(concatenatedString)
}

Output

apple, banana, cherry, date, elderberry

Summary

In this Kotlin tutorial, we learned about reduce() extension function of List: the syntax and few working examples with output and detailed explanation for each example.