iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Mobile Development

Kotlin Android 30天,從 0 到 ML (Machine Learning)系列 第 7

Kotlin Android 第7天,從 0 到 ML - list 、set 和 map

前言:

   今天要介紹的是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])

https://ithelp.ithome.com.tw/upload/images/20210912/20121643m7AcozNp9T.png

取不到回傳空白

   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://ithelp.ithome.com.tw/upload/images/20210912/20121643QJbxJXXQmL.png

參考:

 https://kotlinlang.org/docs/list-operations.html 
 https://kotlinlang.org/docs/set-operations.html
 https://kotlinlang.org/docs/map-operations.html

上一篇
Kotlin Android 第6天,從 0 到 ML - null safety ​
下一篇
Kotlin Android 第8天,從 0 到 ML - 定義類別 / 初始化 / 繼承
系列文
Kotlin Android 30天,從 0 到 ML (Machine Learning)30

尚未有邦友留言

立即登入留言