Kotlin Tutorials

Kotlin Set reduce()
Syntax & Examples

Set.reduce() extension function

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


Syntax of Set.reduce()

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

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

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

Parameters

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

Return Type

Set.reduce() returns value of type S.



✐ Examples

1 Summing elements in a set of integers

Using reduce() to sum the elements in a set of integers.

For example,

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

Kotlin Program

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

Output

15

2 Concatenating strings in a set

Using reduce() to concatenate the strings in a set.

For example,

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

Kotlin Program

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

Output

Kotlin is fun

3 Calculating the product of elements in a set of integers

Using reduce() to calculate the product of the elements in a set of integers.

For example,

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

Kotlin Program

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

Output

24

Summary

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