Kotlin 集合
1.四个基本接口
- Iterable ——所有集合的父类
- MutableIterable —— 继承于Iterabl接口,支持遍历的同时可以执行删除操作
- Collection —— 继承于Iterable接口,仅封装了对集合的只读方法
- MutableCollection ——继承于Iterable,Collection,封装了添加或移除集合中元素的方法
2.类型分类
- List集合
- Map集合
- Set集合
3.可变和不可变两种
- List ——声明不可变List集合
- MutableList——声明可变List集合
- Map——声明不可变Map集合
- MutableMap——声明可变Map集合
- Set——声明不可变Set集合
- MutableSet——声明可变Set集合
创建
// 创建 list
val numbers = listOf("one", "two", "three", "four")
val numbers = mutableListOf(1, 2, 3, 4)
// set
val numbers = setOf(1, 2, 3, 4)
val numbersBackwards = mutableSetOf(1,2,3,4)
// map
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap.put("three", 3)
numbersMap["one"] = 11
空集合
emptyList()、emptySet()与emptyMap()。 创建空集合时,应指定集合将包含的元素类型
val empty = emptyList<String>()
val empty = emptySet<String>()
val empty = emptyMap<String>()
复制
toList()、toMutableList()、toSet()
fun main() {
val array = arrayOf(1,2,3,4)
val copyArray = array.toList().toMutableList()
copyArray.add(2)
println(array.size)
println(copyArray.size)
}
// 源码
public fun <T> Array<out T>.toList(): List<T> {
return when (size) {
0 -> emptyList()
1 -> listOf(this[0])
else -> this.toMutableList()
}
}
public fun <T> Collection<T>.toMutableList(): MutableList<T> {
return ArrayList(this)
}
切片(Slice)
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.slice(1..3))
println(numbers.slice(0..4 step 2))
println(numbers.slice(setOf(3, 5, 0)))
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.take(3))
println(numbers.takeLast(3))
println(numbers.drop(1))
println(numbers.dropLast(5))
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.takeWhile { !it.startsWith('f') })
println(numbers.takeLastWhile { it != "three" })
println(numbers.dropWhile { it.length == 3 })
println(numbers.dropLastWhile { it.contains('i') })
val numbers = (0..13).toList()
println(numbers.chunked(3))
聚合操作
Kotlin集合包含常用聚合操作的函数 - 根据集合内容返回单个值的操作。
---min()和max()分别返回最小和最大元素;
---average()返回数字集合中元素的平均值;
---sum()返回数字集合中元素的总和;
---count()返回集合中元素的数量;
比较器检索最小和最大元素:
----maxBy()/ minBy()接受一个选择器函数并返回它返回最大值或最小值的元素。
----maxWith()/ minWith()获取Comparator对象并根据该Comparator返回最大或最小元素。
val numbers = listOf(6, 42, 10, 4)
println("Count: ${numbers.count()}")
println("Max: ${numbers.max()}")
println("Min: ${numbers.min()}")
println("Average: ${numbers.average()}")
println("Sum: ${numbers.sum()}")
val numbers = listOf(5, 42, 10, 4)
val min3Remainder = numbers.minBy { it % 3 }
println(min3Remainder)
val strings = listOf("one", "two", "three", "four")
val longestString = strings.maxWith(compareBy { it.length })
println(longestString)