Kotlin 数组 - indexOfLast() 函数



Kotlin 数组 indexOfLast() 函数用于返回 ArrayList 中最后一个满足给定谓词的元素的索引。如果没有任何元素匹配给定谓词,则返回 -1。

最后一个元素的索引表示如果存在两个具有相同值的元素,此函数将返回最后一个元素的索引。

语法

以下是 Kotlin 数组 indexOfLast() 函数的语法:

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

参数

此函数接受一个 **谓词** 作为参数。谓词表示一个返回布尔值的条件。

返回值

此函数返回从后往前第一个满足谓词的元素的索引。否则返回 -1。

示例 1

以下是一个演示 indexOfLast() 函数用法的基本示例:

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

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

输出

执行上述代码后,我们将得到以下结果:

The ArrayList is [5, 6, 6, 7]
The last index of even element is 2

示例 2

现在,让我们来看另一个示例。在这里,我们使用 **indexOfLast()** 函数显示长度大于 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.indexOfLast { it.length > 5 }
   
   // Print the array elements
   println("Array: [${array.joinToString { "$it" }}]")
   
   if (indx != -1) {
      println("The last 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 last element with length more than 5 is at index 2, which is "tutorix" with length 7

示例 3

下面的示例创建一个数组。然后我们使用 **indexOfLast** 函数显示最后一个可被 4 整除的元素的索引:

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

输出

上述代码产生以下输出:

The last element which is divisible by 4 is 8 at index: 6
kotlin_arrays.htm
广告
© . All rights reserved.