- 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
廣告