今天要介紹的是list set 和 map。
List 是只可讀 , 不可修改
var list :List<String> = listOf("i","r","o","m", "m","a","n")
//list[3] = "n" IDE 不允許修改
println("list[3] = "+list[3])
取不到回傳空白
println("getOrElse 取不到回傳空白 = "+list.getOrElse(7) {""})
取不到回傳 null
println("getOrNull 取不到回傳null = "+list.getOrNull(7)) //null
Contains 判斷元素,是否包含在 List 集合內
println(list.contains("i")) //true
println(list.containsAll(listOf("i", "m"))) //true
MutableList 是可讀寫,可以修改
var mList:MutableList<String> = mutableListOf("i","t","h","o","n","e")
println("before mList[4] = "+mList[4])
mList[4] = "m" //hone 要改 home
println("Change mList[4] = "+mList[4])
新增add
mList.add("d")
println("add d = "+mList)
刪除remove
mList.remove("d")
println("remove d = "+mList)
再刪一次一樣值 remove again
mList.remove("d")
println("remove d = "+mList)
用index來刪除 remove by index
mList.removeAt(0)
println("removeAt by Index = "+mList)
List ForEach
list.forEach { println("ForEach list = "+it) }
List ForEachIndex
list.forEachIndexed { index, value ->
println("$index, $value")
}
Set 和list不同的地方,就是set裡面的內容不可重覆
val set = setOf("i","r","o","m", "m","a","n")
println(" Set = "+set) // i r o m a n
val mSet = mutableSetOf("i","r","o","m", "m","a","n")
println(" mSet = "+set) // i r o m a n
contains判斷元素,是否包含在 Set 集合內
println(set.contains("i")) //true
println(set.elementAt(0)) //A
Map 用 "to" 給值
var kotlin_team = mapOf("total_day" to 30, "start_day" to 96, "end_day" to 105)
println("kotlin_team = "+kotlin_team)
Map 新增 add key value
kotlin_team += "after_day" to 7
println("add key value kotlin_itaiwan = "+kotlin_team)
Map 用 "Pair" 給值
var kotlin_itaiwan = mapOf(Pair("total_day" , 30), Pair("start_day" ,96) ,
Pair("end_day", 105))
println("kotlin_itaiwan = "+kotlin_itaiwan)
Map 新增add key value
kotlin_itaiwan += "after_day" to 7
println("add key value kotlin_itaiwan = "+kotlin_itaiwan)
Map 取值 , 變數["key"]
println("kotlin_team[total_day] = "+kotlin_team["total_day"])
執行結果:
https://kotlinlang.org/docs/list-operations.html
https://kotlinlang.org/docs/set-operations.html
https://kotlinlang.org/docs/map-operations.html