Sling Academy
Home/Kotlin/Using `for` Loops to Iterate Over Collections in Kotlin

Using `for` Loops to Iterate Over Collections in Kotlin

Last updated: December 05, 2024

When coding in Kotlin, one of the most common tasks is iterating over collections such as lists, sets, and maps. Whether you are processing data, transforming elements, or simply iterating for traversal, the for loop provides an efficient and readable way to automate these tasks.

Basic Iteration

To start off, let’s look at a simple example with a list of integers. In Kotlin, you can use the for loop directly to traverse through each element:

val numbers = listOf(1, 2, 3, 4, 5)
for (number in numbers) {
    println(number)
}

In this example, the variable number represents each element in the list numbers as the loop runs. The loop will iterate from the first element to the last, printing out each number.

Iteration with Indices

Sometimes, you may need not only the element but also its index. Kotlin makes it straightforward to achieve this using the withIndex() function:

val students = listOf("Alice", "Bob", "Charlie")
for ((index, student) in students.withIndex()) {
    println("Student #$index is $student")
}

Here the withIndex() function is used, which returns a set of pairs containing the index and the element at that index, allowing you to access both simultaneously.

Iterating Over a Range

Kotlin also supports iteration over ranges directly within the for loop:

for (i in 1..5) {
    println("i = $i")
}

The above code initializes a range from 1 to 5, inclusive, and the loop iterates over each number in this range.

Stepping Through Ranges

If you want to increase the step size rather than moving one at a time, you can use the step function:

for (i in 1..10 step 2) {
    println(i)
}

This causes the loop to increment by two each time, iterating over the sequence of odd numbers between 1 and 10.

Iterating Backwards

Similarly, you can also iterate backwards using downTo:

for (i in 10 downTo 1) {
    println(i)
}

The above loop counts down from 10 to 1, inclusive.

Iteration Over Maps

Iterating over a map works a bit differently, as each item is a key-value pair. You can easily access these pairs in a for loop:

val map = mapOf(1 to "One", 2 to "Two", 3 to "Three")
for ((key, value) in map) {
    println("Key: $key, Value: $value")
}

Here, the loop provides access to both the key and the value at each iteration, making manipulation straightforward.

Nested Loops

Kotlin allows for nested loops, useful for processing multidimensional collections or matrices. Here’s a quick example:

val matrix = arrayOf(
    intArrayOf(1, 2, 3),
    intArrayOf(4, 5, 6),
    intArrayOf(7, 8, 9)
)

for (row in matrix) {
    for (cell in row) {
        print("$cell ")
    }
    println()
}

This example demonstrates how to iterate through a two-dimensional array, printing each row of numbers in sequence.

Kotlin Best Practices for Iteration

While iterating with for loops is intuitive, it’s important to note that for more advanced cases or processing, Kotlin provides additional ways like forEach, lambda expressions, and sequence operations. These often provide more concise code and better performance on larger data sets due to lazy evaluation.

Always consider the size and nature of the collection you are working with, and whether performance improvements through more modern practices might be beneficial.

Next Article: How to Use `for` Loops with Ranges in Kotlin

Previous Article: Introduction to Loops in Kotlin

Series: Control Flow in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin