1.集合的可变与不可变
kotlin存在三种常用的集合
1.List是一个有序的,可以通过索引访问元素的集合,可以存在重复元素;
2.Set是唯一元素的集合,一般来说无固定顺序;
3.Map是一种键值对集合,键值是唯一的,值可以重复。
1.1不可变集合
fun main() {
val stringList = listOf("one","two","one")
// stringList.add("four") 错误,不可变集合不能添加元素了
println(stringList)
val stringSet = setOf<String>("one","two","one")
//两个one,只输出一个
println(stringSet)
val stringMap = mapOf<Int,String>(Pair(1,"w"),Pair(2,"q"),Pair(1,"r"))
println(stringMap)
}
输出如下:
[one, two, one]
[one, two]
{1=r, 2=q}
[2, 3, 4, 3]
1.2可变集合
val stringList = mutableListOf("one","two","one")
println(stringList)
val stringSet = mutableSetOf<String>("one","two","one")
println(stringSet)
val stringMap = mutableMapOf<Int,String>(Pair(1,"w"),Pair(2,"q"),Pair(1,"r"))
println(stringMap)
//输出如1.1中的一样
可见每个集合都有对应的可变与不可集合
1.3集合排序
kotlin封装了一些基本的集合排序方法,如下
fun sort() {
val numberList = mutableListOf(1, 2, 34, 5)
//随机打乱数据顺序
numberList.shuffle()
println(numberList)
//从小到大排序
numberList.sort()
println(numberList)
//从大到小排序
numberList.sortDescending()
println(numberList)
}
输出结果如下:
[2, 5, 34, 1]
[1, 2, 5, 34]
[34, 5, 2, 1]
fun stuSort(){
val stuList : MutableList<Stu> = mutableListOf()
stuList.add(Stu("xiaoLi",10))
stuList.add(Stu("xiaoHua",21))
stuList.add(Stu("xiaoMen",11))
stuList.add(Stu("xiaoK",13))
//按照age升序排列
stuList.sortBy { it.age }
println(stuList)
//优先name排序,再按照age升序排列
stuList.sortWith(compareBy({it.name},{it.age}))
println(stuList)
}
输出结果如下
[xiaoLi-10, xiaoMen-11, xiaoK-13, xiaoHua-21]
[xiaoHua-21, xiaoK-13, xiaoLi-10, xiaoMen-11]
1.4集合中的Set与Map
fun setAndMap(){
//自动过滤重复元素
val hello = mutableSetOf("h","e","l","l","o")
hello.remove("o")
println(hello)
//集合的加减操作
hello+= setOf("w","o","r","l","d")
hello.add("p")
println(hello)
val numbersMap = mapOf("key1" to 1,"key2" to 2,"key3" to 3,"key4" to 4)
println("All keys : ${numbersMap.keys}")
println("All values : ${numbersMap.values}")
if ("key2" in numbersMap) println("value by key \"key2\":${numbersMap["key2"]}")
if (1 in numbersMap.values) println("1 is in the map")
if (numbersMap.containsValue(1)) println("1 is in the map")
}
输出结果如下:
[h, e, l]
[h, e, l, w, o, r, d]
All keys : [key1, key2, key3, key4]
All values : [1, 2, 3, 4]
value by key "key2":2
1 is in the map
1 is in the map
网友评论