Kotlin基础-集合类型 Map

/*
* 集合类型 Map:无序可重复 类似于“字典”的概念
* 主要属性:Keys(Set),values
*主要方法:
*
* */
fun main(args: Array<String>) {
    //mapof<Key,Value>(Pair(key,value)....)
    //显示指定类型,可防止初始化值填写类型的错误
    val airports= mapOf<String ,String>(Pair("PVG","浦东"),Pair("SHA","虹桥"),Pair("HGH","萧山"))

    //元素计数:size,空否 :isEmpty()
    println(airports.size)

    //获取某个Key对应的value; get,getOrDefult
    print(airports.get("PVG"))
    print(airports.getOrDefault("PVG","不存在值"))
    //返回所有的Key:keys,所有的值value:values
    for (key in airports.keys) {
        print(key)//--->>PVG SHA HGH
    }
    for (v in airports.values) {
        print(v)//---->>浦东虹桥萧山
    }

//转化为可变:toMutableMap
    //mutableMapof<Key,Value>(Pair(key,value),....)
    val airports2=airports.toMutableMap()
//添加或更新:下标方法 map变量名[key]=value
    airports2["DLC"]="大连机场"
    airports2["PVG"]="上海国际机场"
    for (mutableEntry in airports2) {
        println("${mutableEntry.key},${mutableEntry.value}")
    }
    //移除元素:remove
    airports2.remove("PVG")
    for (mutableEntry in airports2) {
        println("${mutableEntry.key},${mutableEntry.value}")
    }
}
原文地址:https://www.cnblogs.com/my334420/p/7070784.html