Updated July 4, 2023
Introduction to Kotlin reduce
Kotlin reduce is one of the default methods in the language used to transform or convert the given set of data collections into a single set of output results. It also takes the lambda function to operate and combine the pair of data elements. It traverses from the left side to the right side of data collection. It steps to accumulate the values with the next elements; it performs the special task of breaking the codes regarding the large modules into smaller modules to make the program more manageable and returns the corresponding values.
Syntax
The kotlin language has many default methods. Keywords and operators create the application deployment, and it’s faster compared to java type of applications. It’s a lightweight component that prevents the applications from increasing memory sizes.
fun main()
{
val vars
println(vars.reduce{x,vars->x+vars})
-----some codes which depends on the requirement----
}
The above codes are the basic syntax for the kotlin reduce() function used on the main method. We can import the packages based on the classes and methods which will use in the code. The reduce() function reduces the sizes and prints the values on the output console.
How does reduce Function Work in Kotlin?
The kotlin language is cross-platform and a Java standard library, but the type is inference. The reduce() is one of the built-in functions that accumulates the values. It may be of any type, like an integer or number, strings starting with the index element, and it applies the code operation from left to the right set of values will be assigned for each set of elements. The values declared by the specific variable types will be array types; the value starts from the index 0.
Using the reduceIndexed() function also returns the array index; if the array is empty, it throws the exception and returns the null value if the array value is empty. The function parameter is a must for the function invoked and each subsequent data element on the group. The data is to be key-value pair formats like a map it associates with the key of each type of group with the formatted results of accumulating the group elements on the stack memory because the method performs the operation that is related to the memory areas for storing the complex values into the single set format values.
Examples of Kotlin reduce
Given below are the examples:
Example #1
Code:
import kotlin.collections.*
fun main() {
val x = listOf(12,34,56,78,90,627, 54,56,65324,65,62145)
val y = x.reduce { y, vars -> y + vars }
println("Have a Nice Day users its the first example regarding the reduce() "+y)
val z = x.fold(2) { y, vars -> y + vars * 5}
println("Thank you users for spenting the time please try again "+z)
val ab = listOf("First", "Welcome", "To", "My","Domain")
println(ab.reduce { cd, vars1 -> cd + vars1 })
val ef = listOf("second", "Please", "Try", "Again","Have", "A", "Nice", "Day", "Users","123","456","789")
println(ef.reduce { gh, vars2 -> gh + vars2 })
}
Output:
In the above example, we used some collection with the reduce() method to reduce the lines from left to right. Currently, the reduce() method converts the values like integer numbers into the single set of values stored on the variable.
Example #2
Code:
import kotlin.collections.*
fun main(args: Array<String>) {
try {
val p = intArrayOf(11, 22, 33, 44, 55, 66, 77, 88, 99)
println(p.sum())
println(p.fold(2){cd, ex -> cd + ex})
var x = 0
p.forEach { x += it }
println(x)
println(p.reduce { q, ex -> q + ex })
val vars = 11/ 0
println(vars)
} catch (ex: ArithmeticException) {
println(ex)
} finally {
println("If above two blocks are not executing means the finally block will execute")
}
println("This is a Second Example")
var w: String = "Welcome To My Domain its a Second Example for to use the reduce() method in Kotlin java library"
println("Have a Nice Day users : $w")
var u: String? = "Thank you for choosing our application Please try again"
println("Its a Second variable $u")
u = null
println("If the variable is going to be null : $u")
}
Output:
In the second example, we used exceptions like arithmetic expressions if we divide the number by infinity. Here we used to try, catch, and finally, blocks for executing the code inside that we used to reduce() method to try the blocks, which depends on the logic.
Example #3
Code:
package one
fun main(args: Array<String>) {
val example1: Int = 33
val example2: Int = 53
val sum = example1 + example2
println("The sum is: $sum")
val example3 = listOf("first", "second", "third", "four", "five", "six", "seven", "eight", "nine", "ten")
val example4 = example3.groupingBy { it.first() }
.fold({ key, _ -> key to mutableListOf<String>() },
{ _, accumulator, element ->
accumulator.also { (_, list) -> if (element.length % 2 == 0) list.add(element) }
})
val example5 = example4.values.sortedBy { it.first }
println(example5)
val example6 = listOf("first", "second", "third", "four", "five", "six", "seven", "eight", "nine", "ten")
val example7 = example3.groupingBy { it.first() }
.fold(listOf<String>()) { acc, e -> if (e.length % 2 == 0) acc + e else acc }
println(example7)
val nums = listOf(44, 45, 43, 22, 11, 72, 61, 83, 94)
val nums1 = nums.reduce { nums1, vars -> nums1 + vars }
val mp = HashMap<Int, String>()
mp.put(1, "siva")
mp.put(2, "raman")
mp.put(3, "welcome")
mp.put(4, "users")
mp.put(5, "have")
mp.put(6, "a")
mp.put(7, "nice")
mp.put(8, "day")
val akeys = ArrayList(mp.keys)
val avalues = ArrayList(mp.values)
println("Your input keys are : $akeys")
println("Your input values are: $avalues")
val y = listOf("four", "five", "six", "second", "first", "seven", "eight", "nine", "ten")
val res= y.reduceRight{ news, eg -> "$eg-$news" }
println(res)
}
Output:
In the final example, we used the collection concepts like list and map and converted the map values to the list collection. Here we used to reduce() and reduceRight() methods for reducing the code lines from left to right and right to left.
Conclusion
In the kotlin language, we used some default methods, keywords, and variables, which regarding the separate packages, include classes and methods. For that, the reduce() and other similar methods are the default methods for reducing the datas into a single set in the collections, util, and other default packages, which depend on the user requirement.
Recommended Articles
We hope that this EDUCBA information on “Kotlin reduce” was beneficial to you. You can view EDUCBA’s recommended articles for more information.