Kotlin Array - indexOfFirst() Function



The Kotlin array indexOfFirst() function is used to return the index of the first element of the ArrayList that satisfies the provided predicate. If no element matches the provided predicate function, then -1 is returned.

The index of first element suggests that if there are two elements with the same value, this function returns the index of the first one.

Syntax

Following is the syntax of Kotlin array indexOfFirst() function −

fun <T> Array<out T>.indexOfFirst(predicate: (T) -> Boolean): Int

Parameters

This function accepts a predicate as a parameter. Predicate represent a condition which gives boolean value.

Return value

This function returns an index of element that first satisfy the predicate. Otherwise; -1.

Example 1

Following is the basic example to demonstrate the use of indexOfFirst() function −

fun main(args: Array<String>) {
   var list = ArrayList<Int>()
   list.add(5)
   list.add(6)
   list.add(7)
   println("The ArrayList is $list")

   var firstIndex = list.indexOfFirst({it % 2 == 0 })
   println("\nThe first index of even element is $firstIndex")
}

Output

On execution of the above code we get the following result −

The ArrayList is [5, 6, 7]
The first index of even element is 1

Example 2

Now, let's see another example. Here, we use the indexOfFirst() function to display the index of first element having length more than 5 −

fun main(args: Array<String>) {
   // let's create an array
   var array = arrayOf("tutorialspoint", "India", "tutorix", "India")
   
   // Find the index of the first element with a length greater than 5
   val indx = array.indexOfFirst { it.length > 5 }
   
   // Print the array elements
   println("Array: [${array.joinToString { "$it" }}]")
   
   if (indx != -1) {
      println("The first element with length more than 5 is at index $indx, which is \"${array[indx]}\" with length ${array[indx].length}")
   } else {
      println("No element has length more than 5.")
   }
}

Output

After execution of the above code we get the following output −

Array: [tutorialspoint, India, tutorix, India]
The first element with length more than 5 is at index 0, which is "tutorialspoint" with length 14

Example 3

The below example creates an array. We then use indexOfFirst function to display the index of the first element which is divisible by 3 −

fun main(args: Array<String>){
   // let's create an array
   var array = arrayOf<Int>(1, 2, 3, 6, 4, 5)
   // using indexOfFirst
   val indx = array.indexOfFirst({it%3==0})
   if(indx == -1){
      println("The element is not available in the array!")
   }else{
      println("The element which is divisible by 3 is ${array[indx]} at index: $indx")
   }
}

Output

The above code produce following output −

The element which is divisible by 3 is 3 at index: 2
kotlin_arrays.htm
Advertisements