Kotlin is a contemporary programming language noted for its simple syntax and extensive feature set. Developers commonly utilize it for Android app development and Java Virtual Machine (JVM) applications.
forEach()
method The forEach()
function loops across collections, doing the specified action on each element. This method makes it easier to conduct operations on each collection element, whether it's a list, array, or other data structure.
The basic syntax of the forEach()
method is as follows:
collection.forEach { element -> // Perform operation on 'element'}
collection
represents the collection you want to iterate through.
element
represents the placeholder for the current element being processed.
Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.
Let’s demonstrate the usage of the forEach()
method with the code given below.
Suppose we have a list of numbers, and we want to calculate the squares of each number present in the list.
fun main() {val numbers = listOf(1, 2, 3, 4, 5)println("Original Numbers: $numbers")numbers.forEach { number ->println("Square of $number: ${number * number}")}}
Line 1–2: Firstly, we define a list of numbers.
Line 4: Next, we display the original list of numbers.
Line 6–7: Finally, we use the forEach()
method to iterate through the numbers
list, and apply the operation to square each element. We print the resulting squares of numbers on the console.
Upon execution, the code calculates the squares of each number in the list by using the forEach()
method.
The output of the code looks like this:
Original Numbers: [1, 2, 3, 4, 5]Square of 1: 1Square of 2: 4Square of 3: 9Square of 4: 16Square of 5: 25
Therefore, the forEach()
method in Kotlin is a powerful tool for iterating through collections and performing operations on their elements. It is an important developer asset, given its improved readability and code efficiency. It helps optimize data processing tasks by using this function.