funmain(){//1.创建list集合val list =mutableListOf("zhangsan","lisi","lisi")//转set去重println(list.toSet())//结果:[zhangsan, lisi]//转set再转listprintln(list.toSet().toList())//结果:[zhangsan, lisi]//快捷函数去重println(list.distinct())//结果:[zhangsan, lisi]}
kotlin语言map
1.kotlin语言map集合的创建与元素的获取
funmain(){/*创建map*///方式1val map1 =mapOf("lisi"to34,"zhagnsan"to55)//方式2val map2 =mapOf(Pair("lisi",22),Pair("zhangsan",55))/*获取元素*///方式1println(map1["lisi"])//结果:34println(map1["lisisdfsf"])//结果:null(没找到对应的value)//方式2println(map1.getOrDefault("lisi",-1))//结果:34println(map1.getOrDefault("lisisdfsf",-1))//结果:-1(没找到对应的value)//方式3println(map1.getOrElse("lisisdfsf"){-1})//结果:-1(没找到对应的value)//方式4(不建议使用)println(map1.getValue("lisisdfsf"))//结果:会崩溃(没找到对应的value)Key lisisdfsf is missing in the map.}
2.kotlin语言map的遍历
funmain(){val map =mapOf("lisi"to34,"zhagnsan"to55)//方式1
map.forEach{println("${it.key}:${it.value}")//结果:lisi:34 zhagnsan:55}//方式2
map.forEach{ key, value ->println("${key}:${value}")//结果:lisi:34 zhagnsan:55}//方式3
map.forEach{(k,v)->println("${k}:${v}")//结果:lisi:34 zhagnsan:55}//方式4(不推荐)for(item in map){println("${item.key}:${item.value}")//结果:lisi:34 zhagnsan:55}}