- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get the current index of an array while using forEach loop in Kotlin?
Sometimes it becomes necessary to access the index of an array. In this article, we will see how we can access the index of an array in Kotlin while using forEach loop.
Example: Using forEachIndexed()
nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible.
In the following example, we will traverse through the "Subject" array and we will print the index along with the value.
Example
fun main() { var subject = listOf("Java", "Kotlin", "JS", "C") subject.forEachIndexed {index, element -> println("index = $index, item = $element ") } }
Output
It will generate the following output −
index = 0, item = Java index = 1, item = Kotlin index = 2, item = JS index = 3, item = C
Example: Using withIndex()
withIndex() is a library function of Kotlin using which you can access both the index and the corresponding values of an array. In the following example, we will be using the same array and we will be using withIndex() to print its values and index. This has to be used with a for loop.
Example
fun main() { var subject=listOf("Java", "Kotlin", "JS", "C") for ((index, value) in subject.withIndex()) { println("The subject of $index is $value") } }
Output
It will generate the following output −
The subject of 0 is Java The subject of 1 is Kotlin The subject of 2 is JS The subject of 3 is C
- Related Articles
- Multiple index variables in PHP foreach loop
- How do we use foreach statement to loop through the elements of an array in C#?
- How to get the selected index of a RadioGroup in Android using Kotlin?
- How do you use ‘foreach’ loop for iterating over an array in C#?
- How to get the current GPS location programmatically on Android using Kotlin?
- Using foreach loop in arrays in C#
- How to use the foreach loop parallelly in PowerShell?
- How to show current progress while downloading a file on Android App using Kotlin?
- How to get the current date and time from the internet in Android using Kotlin?
- How to show a foreach loop using a flow chart in JavaScript?’
- How can I get the current Android SDK version programmatically using Kotlin?
- How to get the current local date and time in Kotlin?
- foreach Loop in C#
- How can we get the current language selected in the Android device using Kotlin?
- How does the Java “foreach” loop work?
