简介
- 在kotlin.collections包下,在Java类库的基础之上进行改造实现了不可变集合类,同时Kotlin的集合类中不仅仅可以持有普通对象,而且能够持有函数类型的变量
集合类概述
- Kotlin集合类分为:可变集合类,不可变集合类
- Kotlin集合类继承层次
创建集合类
集合类 | 创建方法 |
---|---|
List | listOf() |
Set | setOf() |
Map | mapOf() |
MutableList | mutableListOf() |
MutableSet | mutableSetOf() |
MutableMap | mutableMapOf() |
eg:
@Test
fun testCollection() {
// 创建不可变list
val list = listOf(1, 2, 3, 4, 5, 6)
// 创建可变MutableList
val mutableList = mutableListOf(1, 2, 3, 4, 5, 6)
list.forEach { println(it) }
list.forEachIndexed { index, i ->
println("list index = ${index}, value = ${i}")
}
// 创建不可变set
val set = setOf(1, 2, 3, 4, 5)
// 创建可变MutableSet
val mutableSet = mutableSetOf(1, 2, 3, 4, 5)
set.forEach {
println(it)
}
set.forEachIndexed { index, i ->
println("set index = ${index}, value = ${i}")
}
// 创建不可变map
val map = mapOf(1 to "a", 2 to "b", 3 to "c")
// 创建可变map
val mutableMap = mutableMapOf(1 to "a", 2 to "b", 3 to "c")
map.forEach { println("key = ${it.key}, value= ${it.value}") }
map.entries.forEach({ println("key = " + it.key + ", value = " + it.value) })
}
// 输出
1
2
3
4
5
6
list index = 0, value = 1
list index = 1, value = 2
list index = 2, value = 3
list index = 3, value = 4
list index = 4, value = 5
list index = 5, value = 6
1
2
3
4
5
set index = 0, value = 1
set index = 1, value = 2
set index = 2, value = 3
set index = 3, value = 4
set index = 4, value = 5
key = 1, value= a
key = 2, value= b
key = 3, value= c
key = 1, value = a
key = 2, value = b
key = 3, value = c
映射函数
- 使用map函数,可以把集合中的元素一次使用给定的转换函数进行映射操作,元素映射之后的心智会存入一个新的集合中,并返回这个新集合
- 在List、Set继承的Iterable接口和Map接口中,都提供了这个map函数。使用map函数的代码示例如下
eg:
@Test
fun testMap() {
val list = listOf(1, 2, 3, 4, 5, 6)
val set = setOf(1,2,3,4,5,6)
println(list.map{it * it}) // [1, 4, 9, 16, 25, 36]
println(set.map{it + 1}) // [2, 3, 4, 5, 6, 7]
println(list.map{it -> listOf(it + 1, it + 2, it + 3, it + 4)}) // [[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10]]
// 将嵌套的listj结构平铺
val flattenList = list.map{it -> listOf(it + 1, it + 2, it + 3, it + 4)}.flatten()
println(flattenList) // [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10]
val flatMapList = list.flatMap { it -> listOf(it + 1, it + 2, it
+ 3, it + 4)}
println(flatMapList) // [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10]
}
过滤函数
@Test
fun testFilter() {
val list = listOf(1, 2, 3, 4, 5)
println(list.filter{it % 2 == 0}) // [2, 4]
println(list.filterIndexed { index, i ->
index % 2 == 0 && i % 2 != 0
}) // [1, 3, 5]
}
排序函数
@Test
fun testReverse() {
val list = listOf(1, 2, 0, 4, 5, 6)
val set = setOf(1, 2, 0, 4, 5, 6)
// reversed()函数直接调用Java的reversed函数
println(list.reversed()) // [6, 5, 4, 0, 2, 1]
println(set.reversed()) // [6, 5, 4, 0, 2, 1]
// sorted()函数直接调用Java的sorted函数
println(list.sorted()) // [0, 1, 2, 4, 5, 6]
println(set.sorted()) // [0, 1, 2, 4, 5, 6]
}
元素去重
@Test
fun testDistinct() {
val dupList = listOf(1,2,2,3,4,5,5,5,5)
println(dupList.distinct()) // [1, 2, 3, 4, 5]
}