1.List集合
1.1 只读List
fun main() {
val list = listOf("Jason", "Jack", "Jacky")
println(list.getOrElse(3){"Unknown"})
println(list.getOrNull(3)?:"Unknown")
}
1.2 可变List
fun main() {
val mutableList = mutableListOf("Jason", "Jack", "Jacky")
mutableList.add("Jimmy")
mutableList.remove("Jack")
mutableList.forEach(::println)
val toList = mutableList.toList()
println(toList===mutableList)
}
1.2.mutator函数
fun main() {
val mutableList = mutableListOf("Jason", "Jack", "Jacky")
mutableList += "Jimmy"
mutableList -= "Jason"
mutableList.removeIf{it.contains("Jack")}
println(mutableList)
}
1.3. 遍历元素
fun main() {
val list = listOf("Jason", "Jack", "Jacky")
for (s in list) {
println(s)
}
list.forEach{
println(it)
}
list.forEachIndexed { index, s ->
println("$index $s")
}
}
1.4 解构语法过滤元素
fun main() {
val list = listOf("Jason", "Jack", "Jacky")
val(zeroIndexEnum,_,twoIndexEnum)=list
println(zeroIndexEnum)
println(twoIndexEnum)
}
2. Set
2.1 只读Set
fun main() {
val set = setOf("Jason", "Jack", "Jacky", "Jack")
val elementAt = set.elementAt(2) //这里用这个方法取下表
val elementAtOrNull = set.elementAtOrNull(5)//这个方法下表越界了,不会抛异常而是给null
println(elementAt)
}
2.2 可变Set集合
fun main() {
val set = mutableSetOf("Jason", "Jack", "Jacky", "Jack")
set+="Jimmy"
println(set)
}
2.3 集合转换与快捷函数
fun main() {
val set = mutableSetOf("Jason", "Jack", "Jacky", "Jack")
set+="Jimmy"
println(set)
val listOf = listOf("Jason", "Jack", "Jacky", "Jack")
val toList = listOf.toSet().toList()//不是一个对象了
val distinct = listOf.distinct()//不会修改原集合
println(listOf)
println(distinct)
}
3.数组类型
import java.io.File
fun main() {
val intArray:IntArray = intArrayOf(10, 20, 30)
val toIntArray:IntArray = listOf(10, 20, 30).toIntArray()
val array:Array<File> = arrayOf(File("xx"), File("xx"))
}
4.Map
4.1 Map的创建
fun main() {
val map:Map<String,Int> = mapOf("Jack" to 20, "Jason" to 18, "Jack" to 30)
mapOf(Pair("Jimmy",20),Pair("Jason",16))
}
4.2 读取Map的值
fun main() {
val map:Map<String,Int> = mapOf("Jack" to 20, "Jason" to 18, "Jack" to 30)
println(map["Jack"])
println(map.getValue("Jack"))
println(map.getOrElse("Rose"){"Unknown"})
println(map.getOrDefault("Rose",0))
}
4.3 Map的遍历
fun main() {
val map:Map<String,Int> = mapOf("Jack" to 20, "Jason" to 18, "Jacky" to 30)
map.forEach{
println("${it.key}, ${it.value}")
}
map.forEach { (key: String, value: Int) ->
println("$key $value")
}
}
4.4 可变Map集合
fun main() {
val map:MutableMap<String,Int> = mutableMapOf("Jack" to 20, "Jason" to 18, "Jacky" to 30)
map += "Jimmy" to 30
map.put("Ji",3)
val orPut = map.getOrPut("Rose") { 18 }//如果没有就添加进去
println(map)
}