
- 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 陣列 - toList() 函式
Kotlin 陣列 toList() 函式用於將陣列轉換為列表。此函式建立一個新的列表例項,其中包含陣列中所有元素,順序相同。
語法
以下是 Kotlin 陣列 toList() 函式的語法:
fun <T> Array<out T>.toList(): List<T>
引數
此函式不接受任何引數。
返回值
此函式返回一個包含陣列中所有元素的列表。
示例 1
以下是一個基本示例,用於演示使用 toList() 函式返回列表:
fun main(args: Array<String>){ var arr = arrayOf(3, 4, 5, 6) print("Array: ") println(arr.joinToString()) // use toList function to convert an array val list = arr.toList() println("list: "+ list) }
輸出
以上程式碼生成以下輸出:
Array: 3, 4, 5, 6 list: [3, 4, 5, 6]
示例 2
讓我們看另一個例子。在這裡,我們使用 toList 函式返回一個包含陣列中元素的列表,順序相同:
fun main() { // array of integers val intArray = arrayOf(1, 2, 3, 4, 5) // Convert the array to a list val intList: List<Int> = intArray.toList() // display the list println(intList) }
輸出
以下是輸出:
[1, 2, 3, 4, 5]
示例 3
下面的示例將陣列轉換為列表以執行列表操作。然後我們顯示學生的成績並計算平均分數:
fun main(args: Array<String>) { val studentScores = arrayOf(45, 78, 88, 56, 90, 67, 33, 82, 58, 94) // Convert the array to a list val scoreList: List<Int> = studentScores.toList() val passingScore = 60 // Filter the list to get scores of students who passed val passingStudents = scoreList.filter { it >= passingScore } println("Students who passed: $passingStudents") // Calculate the average score of passing students val averagePassingScore = if (passingStudents.isNotEmpty()) { passingStudents.average() } else { 0.0 } println("Average score of passing students: $averagePassingScore") }
輸出
以上程式碼產生以下輸出:
Students who passed: [78, 88, 90, 67, 82, 94] Average score of passing students: 83.16666666666667
kotlin_arrays.htm
廣告