Kotlin 陣列 - indexOfFirst() 函式



Kotlin 陣列 indexOfFirst() 函式用於返回 ArrayList 中第一個滿足提供的斷言的元素的索引。如果沒有任何元素匹配提供的斷言函式,則返回 -1。

第一個元素的索引表示,如果存在兩個具有相同值的元素,此函式將返回第一個元素的索引。

語法

以下是 Kotlin 陣列 indexOfFirst() 函式的語法:

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

引數

此函式接受一個斷言作為引數。斷言表示一個給出布林值的條件。

返回值

此函式返回第一個滿足斷言的元素的索引。否則返回 -1。

示例 1

以下是一個基本示例,用於演示 indexOfFirst() 函式的使用:

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")
}

輸出

執行上述程式碼後,我們將獲得以下結果:

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

示例 2

現在,讓我們看另一個示例。在這裡,我們使用indexOfFirst()函式來顯示長度大於 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.")
   }
}

輸出

執行上述程式碼後,我們將獲得以下輸出:

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

示例 3

下面的示例建立一個數組。然後我們使用indexOfFirst函式來顯示第一個能被 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")
   }
}

輸出

上述程式碼將產生以下輸出:

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