Kotlin Set reduceIndexed()
Syntax & Examples


Set.reduceIndexed() extension function

The reduceIndexed() extension function in Kotlin accumulates a value starting with the first element and applying an operation from left to right to the current accumulator value and each element with its index in the original collection.


Syntax of Set.reduceIndexed()

The syntax of Set.reduceIndexed() extension function is:

fun <S, T : S> Set<T>.reduceIndexed(operation: (index: Int, acc: S, T) -> S): S

This reduceIndexed() extension function of Set 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.

Parameters

ParameterOptional/RequiredDescription
operationrequiredA function that takes the current index, the current accumulator value, and an element, and returns the new accumulator value.

Return Type

Set.reduceIndexed() returns value of type S.



✐ Examples

1 Summing elements in a set of integers with index

Using reduceIndexed() to sum the elements in a set of integers while considering the index.

For example,

  1. Create a set of integers.
  2. Use reduceIndexed() with an operation that adds each element to the accumulator while considering the index.
  3. Print the resulting sum.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val sum = numbers.reduceIndexed { index, acc, num -> acc + num + index }
    println(sum)
}

Output

25

2 Concatenating strings in a set with index

Using reduceIndexed() to concatenate the strings in a set while considering the index.

For example,

  1. Create a set of strings.
  2. Use reduceIndexed() with an operation that concatenates each string to the accumulator while considering the index.
  3. Print the resulting concatenated string.

Kotlin Program

fun main() {
    val strings = setOf("Kotlin", "is", "fun")
    val result = strings.reduceIndexed { index, acc, str -> "$acc $index:$str" }
    println(result)
}

Output

Kotlin 1:is 2:fun

3 Calculating the product of elements in a set of integers with index

Using reduceIndexed() to calculate the product of the elements in a set of integers while considering the index.

For example,

  1. Create a set of integers.
  2. Use reduceIndexed() with an operation that multiplies each element to the accumulator while considering the index.
  3. Print the resulting product.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4)
    val product = numbers.reduceIndexed { index, acc, num -> acc * (num + index) }
    println(product)
}

Output

288

Summary

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