学习内容
1.集合类
2.集合类的各种方法以及使用
A:集合类的简介,如下图(内容来源:《kotlin从入门到进阶实战》)

屏幕快照 2020-12-27 下午10.25.20.png

屏幕快照 2020-12-27 下午10.23.24.png

屏幕快照 2020-12-27 下午10.20.58.png

屏幕快照 2020-12-27 下午10.20.28.png
B:代码实例
package day1
fun main(args:Array<String>){
startList()
initList()
mapAlias()
testStuFilter()
testOrder()
testDump()
}
/**
* kotlin集合
* 不仅能持有普通类型对象
*而且可以持有函数类型变量
*
* 集合类存放的都是对象的引用,而非对象本身
* Kotlin集合分为可变集合Mutable和不可变集合Immutable
*
* 常见的集合类:List,Set,Map
*
*/
/**
*
* 去重函数
*/
fun testDump(){
val dumpList = listOf(1,1,1,3,3,3,2,2,2)
println(dumpList.distinct())
}
/**
* 排序函数
*/
fun testOrder(){
val list = listOf(1,2,3,4,5,6,7)
val set = setOf(1,2,3,4,5,6)
println(list.reversed()) //倒序函数
println(set.reversed())
println(list.sorted())//升序函数
println(set.sorted())
}
/**
* 过滤函数
*
*/
data class Student(val name:String,val age:Int){
override fun toString(): String {
return "Student(name=$name,age=$age)"
}
}
fun testStuFilter(){
val slist = listOf(Student("Tim",10), Student("Tom",20), Student("Jim",30))
val last = slist.filter { it.age>18 }
println(last)
val list = listOf(1,2,34,5,6)
//使用下标过滤
val l = list.filterIndexed { index, i -> index%2==1 && i>10 }
println(l)
}
/**
*
* 使用map函数把集合中的元素依次使用转换函数进行映射操作
* 元素映射后会讲元素存入一个新集合,并返回这个集合
*
*/
fun mapAlias(){
val list = listOf(1,2,3,4,5,6,7)
val set = setOf(1,2,3,4)
val map = mapOf(1 to "a",2 to "b",3 to "c")
val l2 = list.map {
it*it
}
val s2 = set.map {
it+1
}
val m2 = map.map {
it.value + "$"
}
println(l2)
println(s2)
println(m2)
val l3 = listOf("a","b","c")
val l4 = l3.map { it-> listOf(it+1,it+2,it+3,it+4,it+4) }
println(l4)
println(l4.flatten()) //把嵌套的list变成一层的平铺结构
val m3 = m2.flatMap {
it->
listOf(it+1,it+2,it+3)
}
println(m3)
}
fun initList(){
val list = listOf(1,2,3,4,5,6,7) //创建不可变集合list
val multableList = mutableListOf(1,2,3,4,5,6) //创建可变集合
list.forEach { println(it) } //遍历集合
//在遍历过程中访问集合下标
list.forEachIndexed { index, i -> println("Index is $index,value is $i") }
println(list)
println(multableList)
val set = setOf(1,2,3,4) //创建不可变set
val mutableSet = mutableSetOf(1,2,3,4) //创建可变set
set.forEach { println(it) }
set.forEachIndexed { index, i -> println("Index is $index,value is $i") }
println(set)
println(mutableSet)
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
map.forEach { t, u -> println("Key is $t,Value is $u") }
map.entries.forEach {
println("Key is "+it.key+",value is :"+it.value)
}
println(map)
println(mutableMap)
//如果创建一个空的集合,需要显式的指定变量的类型
val emptyList :List<Int> = listOf()
val emptySet : Set<Int> = setOf()
val emptyMap:Map<String,Int> = mapOf()
}
fun startList(){
var funList:List<(Int)->Boolean> = listOf(
{it->it%2==0},
{it->it%2==1}
)
val list = listOf(1,2,3,4,5,6,7,8)
println(list.filter(funList[0]))
println(list.filter(funList[1]))
}