list
可以包含重复元素的列表
新建
listOf
- 只读列表 , 不能修改
- 可以通过安全操作符getOrNul,getOrElse来获取元素
var tList = listOf("a" , "v" , "c")
tList.forEach{
println(it)
}
println(tList.getOrNull(3) ?: "d")
mutableListOf
var tList1 = mutableListOf<String>("a" , "v" , "c")
tList1.replaceAll {
println(it)
"aa".takeIf { it == "a" } ?:it
}
println(tList1)
列表互相转化
tList.toMutableList()
tList1.toList()
修改
mutator重载运算符
tList1 +="f"
tList1 -= "a"
直接下标访问
var tList = mutableListOf<>("a" , "v" , "c")
tList[1] = "bb"
遍历
tList.forEachIndexed{i,s->
println("$i , $s")
}
tList.forEach {
println(it)
}
解构 过滤不想要的元素
可以通过解构,将list拆分出来,通过_过滤不想要的元素
val (x , _ , y) = tList
println("$x $y")
去重 distinct
tList.distinct()
set
不包含重复元素,使用方法与list基本类似
- 创建 setOf mutableSetOf
- 获取 elementAt/elementAtOrElse
- 可读写set转化
var set = setOf<String>("a" , "v" , "c")
set.toMutableList()
set.toMutableSet()
var set = mutableSetOf<String>("a" , "v" , "c")
set.elementAt(0) // a
set.elementAtOrNull(3) //null
set.elementAtOrElse(5 ){
println(it) // 5
set.add("unknown")
}
println(set) //[a, v, c, unknown]
array
- 创建arrayOf ,intArrayOf , doubleArrayOf ,FloatArrayOf
map
创建 mapOf mutableMapOf
var map = mutableMapOf<String,Int>("hello" to 1 , "world" to 2 );
var map1 = mutableMapOf<String , Int>(Pair("hello" , 1) , Pair("world",2))
遍历 foreach
其中map1的遍历方式更kotlin
var map = mutableMapOf<String,Int>("hello" to 1 , "world" to 2 );
var map1 = mutableMapOf<String , Int>(Pair("hello" , 1) , Pair("world",2))
map.forEach { t, u -> println("$t - $u") }
map1.forEach{
println("${it.key} - ${it.value}")
}
获取 getOrElse , get
var map = mutableMapOf<String,Int>("hello" to 1 , "world" to 2 );
map.get("hello")
map.getOrDefault("abc" ,0)
map.getOrPut("abc" ){ 3 }
修改 运算符重载+= put
var map = mutableMapOf<String,Int>("hello" to 1 , "world" to 2 , "huya" to 3);
map += "company" to 4