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