Iterate over a list in Kotlin
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.
|
1 2 3 4 5 |
fun main() { val list: List<String> = listOf("One", "Two", "Three") println(list.toString()) } |
2. Using Iterator
You can use a special iterator ListIterator, that additionally allows bi-directional access. To get a normal iterator, use iterator() function.
|
1 2 3 4 5 6 7 8 |
fun main() { val list: List<String> = listOf("One", "Two", "Three") val itr = list.listIterator() // or, use `iterator()` while (itr.hasNext()) { println(itr.next()) } } |
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.
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf("One", "Two", "Three") for (i in list.indices) { println(list[i]) } } |
The for-loop also has another variation called the foreach loop, which can be used to loop through the list.
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf("One", "Two", "Three") for (s in list) { println(s) } } |
Finally, you can use the forEach() function that performs the given action on each list element.
|
1 2 3 4 5 |
fun main() { val list: List<String> = listOf("One", "Two", "Three") list.forEach { println(it) } } |
That’s all about iterating over a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)