Kotlin forEach: Traversing Collections Efficiently 🎯

beginner
23 min

Kotlin forEach: Traversing Collections Efficiently 🎯

Welcome to your Kotlin journey! Today, we'll dive into a powerful and practical feature called forEach. This function is a game-changer when it comes to traversing collections in Kotlin. Let's get started!

Understanding forEach 📝

In simple terms, forEach is a higher-order function that allows you to iterate through each element of a collection (like lists, arrays, or sets) and perform a specific action on them.

Why use forEach? 💡

  • Readability: forEach makes your code cleaner and more readable, as it allows you to write a concise and straightforward loop.
  • Efficiency: forEach is an efficient way to traverse collections, as it avoids the need for explicit indexing.

Basic forEach Example 📝

Let's look at a simple example of using forEach:

kotlin
val numbers = listOf(1, 2, 3, 4, 5) numbers.forEach { number -> println(number) }

In this example, we have a list of numbers. We use the forEach function to iterate through each number and print it to the console. 💻

forEach with Actions 💡

forEach is not limited to printing elements. You can perform any action you want on each element, such as modifying the collection or performing calculations. Here's an example where we double each number in a list:

kotlin
val numbers = listOf(1, 2, 3, 4, 5) numbers.forEach { number -> number *= 2 println(number) }

In this example, we double each number and print the result. Notice that the original list is modified. 💻

forEach with Index 📝

Sometimes, you might need to access the index of the current element while iterating. In such cases, you can use the withIndex function to combine the element and its index. Here's an example:

kotlin
val numbers = listOf(1, 2, 3, 4, 5) numbers.withIndex().forEach { (index, number) -> println("Index: $index, Number: $number") }

In this example, we print the index and number of each element. 💻

Quiz 🎲

Quick Quiz
Question 1 of 1

What does the `forEach` function do in Kotlin?

Remember, practice makes perfect! Try using forEach in your own projects and feel free to come back to CodeYourCraft for more fun and engaging tutorials. Happy coding! 🚀