5 different Kotlin program to iterate through a mutablelist

Kotlin program to iterate through a mutablelist in different ways:

In this post, we will learn how to iterate through a mutablelist in different ways in Kotlin. Mutable list is editable list. We can edit its elements, add and delete any elements. This is a ordered collection and also insertion order is maintained.

Using hasnext():

hasNext can be called on a iterator and that method can detect if anything to iterate or not. If yes, we can call next() to print the current value. Also, it will point to the next value and we can use it again. We will use one while loop. This loop will check if there is any more elements available for iteration or not. Inside the loop, we are using next() to print the current value:

fun main(args: Array<String>) {
    val mutList = mutableListOf("one", 2,3,4)
    val mutListIterator = mutList.listIterator()

    while(mutListIterator.hasNext()){
        print(mutListIterator.next())
    }
}

It will print the below output:

one
2
3
4

Using forEach:

forEach is similar to a for loop. It iterates through the elements one by one and print them out. For example:

fun main(args: Array<String>) {
    val mutList = mutableListOf("one", 2,3,4)

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

It will print:

one
2
3
4

Using for-in loop:

We can also use one for in loop that is similar to forEach:

fun main(args: Array<String>) {
    val mutList = mutableListOf("one", 2,3,4)

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

It will print same output.

Using a for loop:

This method is useful if we want to know the index of an element while iterating. Below is the complete program:

fun main(args: Array<String>) {
    val mutList = mutableListOf("one", 2,3,4)

    for(i in 0 until mutList.size){
        print(mutList[i])
    }
}

Using forEachIndexed :

This method is similar to forEach, but the difference is that it can be used to get the index of the current element that is iterating.

fun main(args: Array<String>) {
    val mutList = mutableListOf("one", 2,3,4)

    mutList.forEachIndexed{i, item -> println("Item in index ${i} : ${item}")}
}

This program will print:

Item in index 0 : one
Item in index 1 : 2
Item in index 2 : 3
Item in index 3 : 4

You might also like: