一、集合的使用
1、不可变集合
val listString= listOf<String>("one","two","one")
println(listString)
输出:[one, two, one]
val setString= setOf<String>("one","two","one")
println(setString)
输出:[one, two]
2、可变集合
val numbers= mutableListOf<Int>(1,2,3,4)
numbers.add(6)
numbers.removeAt(1)
numbers[0]=10
println(numbers)
输出:[10, 3, 4, 6]
val hello= mutableSetOf<String>("h","e","l","l","o")
hello.remove("o")
println(hello)
输出:[h, e, l]
hello+=setOf("0","w","o","r","l","d")
输出: [h, e, l, 0, w, o, r, d]
3、Map集合
val numberMap= mapOf<String,Int>("a" to 1,"b" to 2,"c" to 3,"d" to 4)
println("keys:${numberMap.keys}")
println("values:${numberMap.values}")
if ("a" in numberMap.keys){}
if (2 in numberMap.values){}
输出:
keys:[a, b, c, d]
values:[1, 2, 3, 4]
二、集合的排序
1、随机排序
val number2= mutableListOf<Int>(12,25,20,56,28)
number2.shuffled()
println("随机$number2")
输出:随机[12, 25, 20, 56, 28]
2、从小到大
number2.sort()
println("小大${number2}")
输出:小大[12, 20, 25, 28, 56]
3、从大到小
number2.sortedDescending()
println("大小${number2.sortedDescending()}")
输出:大小[56, 28, 25, 20, 12]
4、条件排序
data class Language(var name:String,var score:Int)
val languageList = mutableListOf<Language>()
languageList.add(Language("java",88))
languageList.add(Language("kotlin",98))
languageList.add(Language("c语言",86))
languageList.add(Language("python",80))
languageList.add(Language("javascript",80))
languageList.sortBy { it.score }
println(languageList)
输出:[Language(name=python, score=80), Language(name=javascript, score=80), Language(name=c语言, score=86), Language(name=java, score=88), Language(name=kotlin, score=98)]
languageList.sortWith(compareBy({it.score},{it.name}))
println(languageList)
输出:[Language(name=javascript, score=80), Language(name=python, score=80), Language(name=c语言, score=86), Language(name=java, score=88), Language(name=kotlin, score=98)]