Kotlin List indexOf()
Syntax & Examples
Syntax of List.indexOf()
The syntax of List.indexOf() function is:
abstract fun indexOf(element: E): IntThis indexOf() function of List returns the index of the first occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing the elements'a', 'b', 'c', 'd'. - We find the index of the first occurrence of
'a'using the ListindexOf()function, which returns the index of the specified element. - The first occurrence of
'a'is at index0inlist1, soindexAwill be0. - Finally, we print the value of
indexAto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d")
val indexA = list1.indexOf("a")
println(indexA)
}Output
0
2 Example
In this example,
- We create a list named
list1containing the elements10, 20, 30, 40. - We find the index of the first occurrence of
30using the ListindexOf()function, which returns the index of the specified element. - The first occurrence of
30is at index2inlist1, soindex30will be2. - Finally, we print the value of
index30to standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(10, 20, 30, 40)
val index30 = list1.indexOf(30)
println(index30)
}Output
2
3 Example
In this example,
- We create a list named
list1containing the elements'apple', 'banana', 'cherry', 'date'. - We try to find the index of the first occurrence of
'grape'using the ListindexOf()function, which returns the index of the specified element. - Since
'grape'is not present inlist1,indexOf()returns-1. - Finally, we print the value of
indexGrapeto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry", "date")
val indexGrape = list1.indexOf("grape")
println(indexGrape)
}Output
-1
Summary
In this Kotlin tutorial, we learned about indexOf() function of List: the syntax and few working examples with output and detailed explanation for each example.