How to find the index of an element in an ArrayList in Kotlin
How to find the index of an element in an ArrayList in Kotlin.
Here's a step-by-step tutorial on how to find the index of an element in an ArrayList in Kotlin:
Step 1: Create an ArrayList
First, you need to create an ArrayList in Kotlin. An ArrayList is a resizable array implementation provided by the Kotlin standard library. You can use the ArrayList class and its constructor to create an ArrayList.
val list = ArrayList<String>()
Step 2: Add elements to the ArrayList
Next, you need to add elements to the ArrayList. You can use the add() method to add elements to the end of the ArrayList. Here's an example of adding some elements to the ArrayList:
list.add("Apple")
list.add("Banana")
list.add("Orange")
Step 3: Find the index of an element
To find the index of a specific element in the ArrayList, you can use the indexOf() method. The indexOf() method returns the index of the first occurrence of the specified element in the ArrayList, or -1 if the element is not found.
val index = list.indexOf("Banana")
In this example, the indexOf() method is used to find the index of the element "Banana" in the ArrayList.
Step 4: Handle the result
The indexOf() method returns a value that represents the index of the element in the ArrayList. You can use this value to perform further operations or display the result. If the element is found, the indexOf() method returns the index of the element. If the element is not found, it returns -1.
if (index != -1) {
println("The index of Banana is $index")
} else {
println("Banana is not found in the list")
}
In this example, the result is displayed as a string using the println() function.
Step 5: Handle multiple occurrences
If there are multiple occurrences of the element in the ArrayList, the indexOf() method returns the index of the first occurrence. If you want to find the index of all occurrences of the element, you can use a loop.
val element = "Apple"
val indices = mutableListOf<Int>()
for (i in list.indices) {
if (list[i] == element) {
indices.add(i)
}
}
if (indices.isNotEmpty()) {
println("The indices of $element are ${indices.joinToString()}")
} else {
println("$element is not found in the list")
}
In this example, a MutableList called indices is used to store the indices of all occurrences of the element "Apple" in the ArrayList.
That's it! You have now learned how to find the index of an element in an ArrayList in Kotlin.