This article explores different ways to iterate over a list in Kotlin.

1. Using toString() function

If you want to display the list’s contents, you can simply print the string representation of the list using the toString() function.

Download Code

2. Using Iterator

You can use a special iterator ListIterator, that additionally allows bi-directional access. To get a normal iterator, use iterator() function.

Download Code

3. Using loop

Since List is an ordered collection, you can use index-based for-loop to access elements by their index in the list.

Download Code

 
The for-loop also has another variation called the foreach loop, which can be used to loop through the list.

Download Code

 
Finally, you can use the forEach() function that performs the given action on each list element.

Download Code

That’s all about iterating over a list in Kotlin.