集合
Kotlin 区分可变集合与不可变集合
容器:数组长度固定,集合长度可变.
数组存储数据,集合存储对象.对象的类型可以不一致
1.分类
1.1 单列集合Collection:
List集合元素有序可重复
Set集合元素无序,不可重复
TreeSet有序不重复的集合
1.2 双列集合Map,存储映射对象
1.3 集合的创建:
Of创建不可变集合,mutableOf创建可变集合.
mutableOf只能用于接口,Of还可用于实现类创建
在非性能关键代码中创建 map 可以用一个简单的惯用法来完成: mapOf(a to b, c to d)
listOf,setOf,mapOf
MutableCollection,mutableListOf,mutableSetOf,mutableMapOf
2.List集合
listOf创建的集合不可变,元素不可修改
fun main(args: Array<String>) {
val list1 = listOf("林青霞","张曼玉","关之琳")
}
mutableListOf创建的集合元素可以修改
val list2 = mutableListOf("林青霞","张曼玉","关之琳")
list2.add("雪儿")
list2.set(1,"李若彤")
或者
val list3 = MutableList<String>(10){
"茵"
} //创建一个10个元素为"茵"的List可变集合
也可使用JAVA的集合体系
val list4 = ArrayList<String>()
val list5 = arrayListOf("张三","李四","王五")
3.Map集合
val map4 = hashMapOf("中国" to "China","英国" to "England","美国" to "USA")
map4.put("中国","Chinese")
val map5 = mutableMapOf("南海" to "南", "东海" to "东")
map5.putAll(map4)
println(map5)
遍历
map.keys
map.values
4.去重复
distinctBy,返回重复的元素集合
toSet,distinct为空参,去除重复的元素,返回集合
fun main(args: Array<String>) {
val list = listOf("张三","李四","李四","王五","赵六","张三","张四","李六")
println(list.distinctBy {
it == "张三"
})
} //[张三, 李四]
5.过滤(find和filter)
find返回集合中第一个满足条件的元素
filter返回集合中满足条件的集合
fun main(args: Array<String>) {
val list2 = listOf("周芷若","张无忌","张五","李善长","林青霞","李寻欢")
val s1 = list2.find {
it.startsWith("张")
}
println(s1) //张无忌
val zhangList = list2.filter {
it.startsWith("张")
}
println(zhangList)
} //[张无忌, 张五]
6.排序 sorted
对汉字字符串排序,只会把姓放在相邻位置
fun main(args: Array<String>) {
val list = listOf("g", "u", "q", "n", "d", "z", "a")
val list1 = list.sorted() //正序排序
println(list1)
val list2 = list.sortedDescending() //倒序排序
println(list2)
val personList = listOf(Person("林青霞",50),Person("张曼玉",30),Person("郑少秋",70))
val list5 = personList.sortedBy { //按字段排序
it.age
}
7.分组 groupBy
fun main(args: Array<String>) {
val list = listOf("张三", "张三", "李四", "王五", "赵六", "张四", "李五", "李六")
val map = list.groupBy {
val firstChar = it.substring(0, 1)
when (firstChar) {
"张" -> "张"
"李" -> "李"
else -> "其它"
}
}
println(map)
}
8.最值 max,min,maxBy,minBy
fun main(args: Array<String>) {
val list = listOf("z", "e", "t", "n")
val max = list.max()
val min = list.min()
val personList = listOf(Person("林青霞",50),Person("张曼玉",30),Person("郑少秋",70))
val maxAge = personList.maxBy { it.age }
println(personList.minBy { it.age })
}
9.集合拆分 partition
fun main(args: Array<String>) {
val list = listOf("张三","李四","王五","赵六","张四","李五","李六")
val pair = list.partition {
it.substring(0,1)=="张"
}
println(pair.first)
println(pair.second)
}
10.集合重新组合(map)
fun main(args: Array<String>) {
val personList = listOf(Person("林青霞",50),Person("张曼玉",30),Person("郑少秋",70))
val nameList = personList.map {
}
println(nameList)
}