Kotlin 获取 List 元素下标:使用 indexOfFirst 和 indices
在 Kotlin 中,可以使用 indexOfFirst 函数来根据 key 获取 List 元素的下标。
示例代码如下:
fun main() {
val list = listOf('apple', 'banana', 'orange', 'grape', 'kiwi')
val key = 'orange'
val index = list.indexOfFirst { it == key }
if (index >= 0) {
println('Found $key at index $index')
} else {
println('$key not found in the list')
}
}
输出结果为:
Found orange at index 2
在上面的示例中,我们使用 indexOfFirst 函数来查找第一个等于 key 的元素,并返回其下标。如果找到了,返回的下标将是大于等于 0 的值;如果没有找到,则返回 -1。
如果你想要查找所有等于 key 的元素的下标,而不只是第一个,可以使用 indices 属性和 filter 函数来实现:
fun main() {
val list = listOf('apple', 'banana', 'orange', 'grape', 'kiwi', 'orange')
val key = 'orange'
val indices = list.indices.filter { list[it] == key }
if (indices.isNotEmpty()) {
println('Found $key at indices $indices')
} else {
println('$key not found in the list')
}
}
输出结果为:
Found orange at indices [2, 5]
在上面的示例中,我们使用 indices 属性获取 List 的索引范围,然后使用 filter 函数过滤出所有等于 key 的元素的下标。最后,我们打印出所有找到的下标。
原文地址: https://www.cveoy.top/t/topic/pjY7 著作权归作者所有。请勿转载和采集!