Kotlin 集合 Set、List、Map 及常用方法
一、Kotlin set 集合
1. kotlin 创建 set 集合
val set1 = setOf(1, 2, 3)
val set2 = mutableSetOf(1, 2, 3)
val set3 = hashSetOf(1, 2, 3)
val set4 = linkedSetOf(1, 2, 3)
val set5 = sortedSetOf(1, 2, 0, -1)
2. kotlin Set 集合常用方法
val set = setOf("kotlin", "java", "swift", "flutter")
val setToMap = set.associateBy { "${it.length}" }
println(setToMap)
set.contains("kotlin")
println("kotlin" in set)
println("swift" !in set)
println(set.drop(3))
println(set.filter { "ft" in it })
println(set.find { "ft" in it })
println(set.find { "python" in it })
println(set.fold("") { acc, ele -> acc + ele })
println(set.indexOf("kotlin"))
println(set.maxOrNull())
println(set.minOrNull())
println(set.reversed())
val setStr = setOf("flutter", "oc")
println(set intersect setStr)
println(set union setStr)
3. kotlin Set 集合遍历
for (item in set) {
println(item)
}
for (index in set.indices) {
println(set.elementAt(index))
}
set.forEach {
println(it)
}
4. kotlin 可变 set 集合
val mutableSet = mutableSetOf("1", "2")
mutableSet.add("3")
mutableSet.addAll(setOf("4", "5", "6"))
mutableSet.remove("6")
mutableSet.removeAll(setOf("4", "5"))
println(mutableSet)
二、Kotlin List 集合
1. kotlin 创建 list 集合
val list1 = listOf(1, 2, 3)
val list2 = listOfNotNull("1", "2", null)
println(list2)
val list3 = mutableListOf(1, 2, 3, 2)
val list4 = arrayListOf(1, 2, 3)
2. kotlin list 集合常用方法
println(list1.get(0))
println(list4[0])
println(list2.indexOf("2"))
println(list3.lastIndexOf(2))
val sub = list3.subList(0, 2)
println(sub)
list4.add(4)
list4.add(0, 1)
list4.remove(element = 4)
list4.removeAt(2)
println(list4)
三、kotlin Map 集合
1. kotlin 创建 map 集合
val map = mapOf("key0" to 0, "key1" to 1)
val map2 = mutableMapOf("key0" to 0, "key1" to 1)
val map3 = hashMapOf("key0" to 0, "key1" to 1)
val map4 = linkedMapOf("key0" to 0, "key1" to 1)
val map5 = sortedMapOf("key0" to 0, "key1" to 1)
2. kotlin map 集合遍历
for (en in map.entries) {
println("key: ${en.key}, value: ${en.value}")
}
for (key in map.keys) {
println("key: ${key}, value: ${map[key]}")
}
for ((key, value) in map) {
println("key: $key, value: $value")
}
map.forEach { (key, value) ->
println("key: $key, value: $value")
}
3. kotlin map 集合常用方法
map2.put("key2", 2)
map3["key3"] = 3
map4.remove("key1")
map5.clear()
附 Github 源码:TestCollection