- Kotlin 教程
- Kotlin - 首页
- Kotlin - 概述
- Kotlin - 环境搭建
- Kotlin - 架构
- Kotlin - 基本语法
- Kotlin - 注释
- Kotlin - 关键字
- Kotlin - 变量
- Kotlin - 数据类型
- Kotlin - 运算符
- Kotlin - 布尔值
- Kotlin - 字符串
- Kotlin - 数组
- Kotlin - 范围
- Kotlin - 函数
- Kotlin 控制流
- Kotlin - 控制流
- Kotlin - if...else 表达式
- Kotlin - when 表达式
- Kotlin - for 循环
- Kotlin - while 循环
- Kotlin - break 和 continue
- Kotlin 集合
- Kotlin - 集合
- Kotlin - 列表
- Kotlin - 集合
- Kotlin - 映射
- Kotlin 对象和类
- Kotlin - 类和对象
- Kotlin - 构造函数
- Kotlin - 继承
- Kotlin - 抽象类
- Kotlin - 接口
- Kotlin - 可见性控制
- Kotlin - 扩展
- Kotlin - 数据类
- Kotlin - 密封类
- Kotlin - 泛型
- Kotlin - 代理
- Kotlin - 解构声明
- Kotlin - 异常处理
- Kotlin 有用资源
- Kotlin - 快速指南
- Kotlin - 有用资源
- Kotlin - 讨论
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
广告