Skip to main content

How to iterate through an ArrayList in Kotlin

How to iterate through an ArrayList in Kotlin.

Here's a detailed step-by-step tutorial on how to iterate through an ArrayList in Kotlin:

  1. Declare an ArrayList:

    val arrayList = arrayListOf("apple", "banana", "cherry")
  2. Iterate using a for loop:

    for (item in arrayList) {
    println(item)
    }

    Output:

   apple
banana
cherry

In this example, the for loop iterates through each item in the arrayList and prints it.

  1. Iterate using an indexed for loop:

    for (i in 0 until arrayList.size) {
    println(arrayList[i])
    }

    Output:

   apple
banana
cherry

Here, the indexed for loop iterates through each index of the arrayList and accesses the element at that index using the square bracket notation.

  1. Iterate using a forEach loop:

    arrayList.forEach { item ->
    println(item)
    }

    Output:

   apple
banana
cherry

The forEach loop is a higher-order function that takes a lambda expression as an argument. It iterates through each item in the arrayList and executes the lambda function.

  1. Iterate using a while loop:

    var index = 0
    while (index < arrayList.size) {
    println(arrayList[index])
    index++
    }

    Output:

   apple
banana
cherry

Here, the while loop iterates through each index of the arrayList and prints the element at that index.

  1. Iterate using a ListIterator:

    val listIterator = arrayList.listIterator()
    while (listIterator.hasNext()) {
    println(listIterator.next())
    }

    Output:

   apple
banana
cherry

The ListIterator provides a way to iterate both forward and backward through a list. In this example, we create a ListIterator from the arrayList and use its hasNext() and next() functions to iterate through the elements.

  1. Iterate using an Iterator:

    val iterator = arrayList.iterator()
    while (iterator.hasNext()) {
    println(iterator.next())
    }

    Output:

   apple
banana
cherry

The Iterator interface provides a way to iterate over a collection. In this example, we create an Iterator from the arrayList and use its hasNext() and next() functions to iterate through the elements.

That's it! You now know how to iterate through an ArrayList in Kotlin using various looping constructs and iterators.