【Kotlin】集合操作 ② ( MutableList 可变列表集合 | 修改 MutableList 集合的 mutator 函数 )
2023-06-13 09:18:07 时间
文章目录
一、MutableList 可变列表集合
使用 listOf 函数 创建的 List 集合 是 只读列表集合 ;
使用 mutableListOf 函数 创建的 MutableList 集合 是 可变列表集合 ;
调用 MutableList#toList 函数 , 可以 将 可变列表集合 转为 只读列表集合 ;
调用 List#toMutableList 函数 , 可以 将 只读列表集合 转为 可变列表集合 ;
代码示例 :
fun main() {
// 创建可变列表集合
var mutableList = mutableListOf("Tom", "Jerry")
// 添加元素
mutableList.add("Jack")
// 删除元素
mutableList.remove("Tom")
println(mutableList)
// 将 可变列表集合 转为 只读列表集合
val list: List<String> = mutableList.toList()
// 将 只读列表集合 转为 可变列表集合
val mutable: MutableList<String> = list.toMutableList()
}
执行结果 :
[Jerry, Jack]
二、修改 MutableList 集合的 mutator 函数
修改 MutableList 集合 的 函数 统称为 mutator 函数 ;
1、添加元素运算符 += 和 删除元素运算符 -=
运算符重载 : MutableList 集合 还有一些 运算符重载 , 添加元素运算符 +=
和 删除元素运算符 -=
;
- 向 MutableList 集合 中添加一些元素 , 可使用 += 运算符 :
mutableList += "Jack"
其效果等同于
mutableList.add("Jack")
- 从 MutableList 集合 中删除一些元素 , 可使用 -= 运算符 :
mutableList -= "Tom"
其效果等同于
mutableList.remove("Tom")
2、通过 Lambda 表达式筛选要删除的元素
通过 Lambda 表达式筛选要删除的元素 : Lambda 表达式返回 boolean 值 , 如果返回 true , 则删除该元素 , 返回 false 则不处理该元素 ;
fun main() {
// 创建可变列表集合
val mutableList = mutableListOf("Tom", "Jerry")
// 通过 Lambda 表达式筛选要操作的元素
// 删除包含 字母 T 的元素
mutableList.removeIf {
it.contains("T")
}
println(mutableList)
}
执行结果 :
[Jerry]
相关文章
- 中国电信营业厅: 感受 Kotlin 的 "加速度"
- Kotlin 学习笔记(二)
- kotlin 和 r8 的量子纠缠 | 类加载机制偷鸡
- Kotlin泛型的型变之路
- kotlin基本语法
- 【Kotlin】函数类型 ( 函数类型 | 带参数名称的参数列表 | 可空函数类型 | 复杂函数类型 | 带接收者函数类型 | 函数类型别名 | 函数类型实例化 | 函数调用 )
- 【错误记录】Kotlin 编译报错 ( Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable ... )
- 【错误记录】Kotlin 报错 ( Some kotlin libraries attached to this project were compiled with a newer kotlin )
- 【Kotlin 协程】协程的挂起和恢复 ② ( 协程挂起 和 线程阻塞 对比 )
- 【Kotlin 协程】Flow 异步流 ⑥ ( 调用 Flow#launchIn 函数指定流收集协程 | 通过取消流收集所在的协程取消流 )
- 【Kotlin 协程】Flow 操作符 ① ( 过渡操作符 | map 操作符 | transform 操作符 | 限长操作符 | take 操作符 )
- 【Kotlin 协程】Flow 流收尾工作 ( finally 代码块收尾 | onCompletion 代码块收尾 | onCompletion 中获取异常信息 | catch 代码块中捕获异常 )
- 【Kotlin 协程】Channel 通道 ③ ( CoroutineScope#produce 构造生产者协程 | CoroutineScope#actor 构造消费者协程 )
- 【Kotlin 协程】协程中的多路复用技术 ② ( select 函数原型 | SelectClauseN 事件 | 查看挂起函数是否支持 select )
- 【Kotlin】标准库函数 ② ( run 标准库函数 | run 函数传入 Lambda 表达式作为参数 | run 函数传入函数引用作为参数 )
- 【Kotlin】标准库函数 ③ ( with 标准库函数 | also 标准库函数 )
- 【Kotlin】接口和抽象类 ( 接口属性和方法定义 | 接口默认方法实现 | 抽象类 )