Kotlin Set runningReduce()
Syntax & Examples
Set.runningReduce() extension function
The runningReduce() extension function in Kotlin returns a list containing successive accumulation values generated by applying an operation from left to right to each element and the current accumulator value that starts with the first element of this collection.
Syntax of Set.runningReduce()
The syntax of Set.runningReduce() extension function is:
fun <S, T : S> Set<T>.runningReduce(operation: (acc: S, T) -> S): List<S>
This runningReduce() extension function of Set 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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
operation | required | A function that takes the current accumulator value and an element, and returns the new accumulator value. |
Return Type
Set.runningReduce() returns value of type List
.
✐ Examples
1 Running sum of elements in a set of integers
Using runningReduce() to calculate the running sum of elements in a set of integers.
For example,
- Create a set of integers.
- Use runningReduce() with an operation that adds each element to the accumulator.
- Print the resulting list of running sums.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val runningSums = numbers.runningReduce { acc, num -> acc + num }
println(runningSums)
}
Output
[1, 3, 6, 10, 15]
2 Running concatenation of strings in a set
Using runningReduce() to calculate the running concatenation of strings in a set.
For example,
- Create a set of strings.
- Use runningReduce() with an operation that concatenates each string to the accumulator.
- Print the resulting list of running concatenations.
Kotlin Program
fun main() {
val strings = setOf("Kotlin", "is", "fun")
val runningConcat = strings.runningReduce { acc, str -> "$acc $str" }
println(runningConcat)
}
Output
[Kotlin, Kotlin is, Kotlin is fun]
3 Running product of elements in a set of integers
Using runningReduce() to calculate the running product of elements in a set of integers.
For example,
- Create a set of integers.
- Use runningReduce() with an operation that multiplies each element to the accumulator.
- Print the resulting list of running products.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4)
val runningProducts = numbers.runningReduce { acc, num -> acc * num }
println(runningProducts)
}
Output
[1, 2, 6, 24]
Summary
In this Kotlin tutorial, we learned about runningReduce() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.