How do I loop through collections using for, foreach and indices in Kotlin?

In Kotlin, you can loop through collections in several common ways depending on whether you need the element, the index, or both.

1. Using for

Use for when you want a simple, readable loop over elements.

val names = listOf("Alice", "Bob", "Charlie")

for (name in names) {
    println(name)
}

Output:

Alice
Bob
Charlie

This works with many Kotlin types, including:

val numbers = arrayOf(1, 2, 3)

for (number in numbers) {
    println(number)
}

2. Using forEach

Use forEach when you prefer a functional style.

val names = listOf("Alice", "Bob", "Charlie")

names.forEach { name ->
    println(name)
}

If the lambda has only one parameter, you can use it:

names.forEach {
    println(it)
}

forEach is useful for concise operations, but a regular for loop is often clearer if you need break, continue, or more complex control flow.


3. Looping with indices

Use indices when you need the index of each element.

val names = listOf("Alice", "Bob", "Charlie")

for (i in names.indices) {
    println("Index $i: ${names[i]}")
}

Output:

Index 0: Alice
Index 1: Bob
Index 2: Charlie

indices gives the valid index range for the collection, such as 0..lastIndex.


4. Using withIndex

If you need both the index and the value, withIndex() is often cleaner than indexing manually.

val names = listOf("Alice", "Bob", "Charlie")

for ((index, name) in names.withIndex()) {
    println("Index $index: $name")
}

5. Using forEachIndexed

The forEach equivalent for index + value is forEachIndexed.

val names = listOf("Alice", "Bob", "Charlie")

names.forEachIndexed { index, name ->
    println("Index $index: $name")
}

Summary

val items = listOf("A", "B", "C")

// Element only
for (item in items) {
    println(item)
}

// Element only, functional style
items.forEach { item ->
    println(item)
}

// Index only / index-based access
for (i in items.indices) {
    println("items[$i] = ${items[i]}")
}

// Index and value
for ((index, item) in items.withIndex()) {
    println("$index -> $item")
}

// Index and value, functional style
items.forEachIndexed { index, item ->
    println("$index -> $item")
}

Use:

  • for (item in items) for simple iteration
  • items.forEach { ... } for concise functional-style iteration
  • items.indices when you need index-based access
  • withIndex() or forEachIndexed when you need both index and value

How do I use ranges and step values in Kotlin for loops?

In Kotlin, you can use ranges and step values in for loops to iterate over a sequence of numbers or characters. Here’s a detailed guide:

1. Ranges in Kotlin

A range is defined using the .. operator. For example:

for (i in 1..5) {
    println(i)
}
  • Output: 1 2 3 4 5
  • The loop iterates from 1 to 5 (both inclusive).

2. Stepping Through a Range

To define the step value, you can use the step function. For instance:

for (i in 1..10 step 2) {
    println(i)
}
  • Output: 1 3 5 7 9
  • The loop starts from 1 and increments by 2 on each iteration.

3. Descending Ranges

If you want to iterate in reverse order, use the downTo function:

for (i in 10 downTo 1) {
    println(i)
}
  • Output: 10 9 8 7 6 5 4 3 2 1

You can combine downTo with step:

for (i in 10 downTo 1 step 2) {
    println(i)
}
  • Output: 10 8 6 4 2

4. Iterating Over Characters

Kotlin ranges also work with characters:

for (ch in 'a'..'e') {
    println(ch)
}
  • Output: a b c d e

You can also provide a step value:

for (ch in 'a'..'z' step 3) {
    println(ch)
}
  • Output: a d g j m p s v y

5. Using until

The until function creates a range that excludes the upper boundary:

for (i in 1 until 5) {
    println(i)
}
  • Output: 1 2 3 4
  • The loop stops before reaching 5.

Summary of Functions and Keywords

  1. ..: Creates a range that includes the start and end values.
  2. downTo: Creates a descending range.
  3. step: Sets the step value for the range.
  4. until: Excludes the upper boundary of the range.

These features make Kotlin’s for loops flexible and expressive.

How do I loop through items using for and while in Kotlin?

In Kotlin, you can use both for and while loops to iterate through items. Here is a quick overview of how you can use these loops with examples:


1. Using a for Loop

A for loop is used to iterate through a range, array, list, or any iterable.

Iterating through a range:

for (i in 1..5) {
    println("Current number is $i")
}
  • 1..5 creates a range from 1 to 5 (inclusive).
  • You can also use until to exclude the end value:
for (i in 1 until 5) {
    println("Current number is $i") // 1 to 4
}
  • To iterate in reverse, use the downTo keyword:
for (i in 5 downTo 1) {
    println("Countdown: $i")
}
  • To skip steps, use the step keyword:
for (i in 1..10 step 2) {
    println("Step: $i")
}

Iterating through a list or array:

val items = listOf("Apple", "Banana", "Orange")
for (item in items) {
    println(item)
}

Iterating with index:

val items = arrayOf("A", "B", "C")
for ((index, value) in items.withIndex()) {
    println("Index: $index, Value: $value")
}

2. Using a while Loop

A while loop is used when you want to execute a block of code as long as a condition is true.

Example of a while loop:

var counter = 1
while (counter <= 5) {
    println("Count: $counter")
    counter++
}

Example of a do-while loop:

The do-while loop ensures the block of code executes at least once.

var counter = 1
do {
    println("Count: $counter")
    counter++
} while (counter <= 5)

Summary of Differences:

  • for Loop: Best for iterating over ranges, collections, and when the number of iterations is known.
  • while (and do-while) Loop: Best for scenarios where the number of iterations depends on a condition.

Why do I get ArrayIndexOutOfBoundsException in Java?

The ArrayIndexOutOfBoundsException exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Array with 10 elements

For example see the code snippet below:

String[] vowels = new String[]{"a", "i", "u", "e", "o"}
String vowel = vowels[10]; // throws the ArrayIndexOutOfBoundsException

Above we create a vowels array with five elements. This will make the array have indexes between 0..4. On the next line we tried to access the tenth element of the array which is illegal. This statement will cause the ArrayIndexOutOfBoundsException thrown.

We must understand that arrays in Java are zero indexed. The first element of the array will be at index 0 and the last element will be at index array-size - 1. So be careful with your array indexes when accessing array elements. For example if you have an array with 5 elements this mean that the index of the array is from 0 to 4.

If you are trying to iterate an array using for loop. Make sure the index start from 0 and execute the loop while the index is less than the length of the array, you can get the length of the array using the array length property. Let’s see the code snippet below:

for (int i = 0; i < vowels.length; i++) {
    String vowel = vowels[i];
    System.out.println("vowel = " + vowel);
}

Or if you don’t need the index you can simplify your code using the for-each or enhanced for-loop statement instead of the classic for loop statement as shown below:

for (String vowel : vowels) {
    System.out.println("vowel = " + vowel);
}