kotlin中的Map集合类
2021-12-15 本文已影响0人
KingWorld
Kotlin中的Map分为:
只读Map。
可变的MutableMap(MutableMap、HashMap、LinkedHashMap)。
Map源码:
private object EmptyMap : Map<Any?, Nothing>, Serializable {
private const val serialVersionUID: Long = 8246714829545688274
override fun equals(other: Any?): Boolean = other is Map<*,*> && other.isEmpty()
override fun hashCode(): Int = 0
override fun toString(): String = "{}"
override val size: Int get() = 0
override fun isEmpty(): Boolean = true
override fun containsKey(key: Any?): Boolean = false
override fun containsValue(value: Nothing): Boolean = false
override fun get(key: Any?): Nothing? = null
override val entries: Set<Map.Entry<Any?, Nothing>> get() = EmptySet
override val keys: Set<Any?> get() = EmptySet
override val values: Collection<Nothing> get() = EmptyList
private fun readResolve(): Any = EmptyMap
}
创建只读Map
val mMap = mapOf(0 to "秦", 1 to "川", 2 to "小", 3 to "将")
println(mMap)
打印输出:
{0=秦, 1=川, 2=小, 3=将}
创建可变Map
mutableMapOf
val mMap = mutableMapOf(0 to "秦", 1 to "川", 2 to "小", 3 to "将")
println("=========向Map中添加元素kotlin,in,android===========")
mMap.put(4, "kotlin")
mMap.put(5, "in")
mMap.put(6, "android")
println(mMap)
println("===========将Map中元素android替换为java=============")
mMap.replace(6, "java")
println(mMap)
println("===========删除Map中元素kotlin,in,java=============")
mMap.remove(4, "kotlin")
mMap.remove(5, "in")
mMap.remove(6, "java")
println(mMap)
println("================清除Map中所有元素===================")
mMap.clear()
println(mMap.size)
打印输出:
=========向Map中添加元素kotlin,in,android===========
{0=秦, 1=川, 2=小, 3=将, 4=kotlin, 5=in, 6=android}
===========将Map中元素android替换为java=============
{0=秦, 1=川, 2=小, 3=将, 4=kotlin, 5=in, 6=java}
===========删除Map中元素kotlin,in,java=============
{0=秦, 1=川, 2=小, 3=将}
================清除Map中所有元素===================
hashMapOf
val mMap = hashMapOf(0 to "秦", 1 to "川", 2 to "小", 3 to "将")
println(mMap)
打印输出:
{0=秦, 1=川, 2=小, 3=将}
linkedMapOf
val mMap = linkedMapOf(0 to "秦", 1 to "川", 2 to "小", 3 to "将")
println(mMap)
打印输出:
{0=秦, 1=川, 2=小, 3=将}
sortedMapOf
sortedMapOf(vararg pairs: Pair
val mMap = sortedMapOf(1 to "川", 3 to "将", 0 to "秦", 2 to "小")
println(mMap)
打印输出:
{0=秦, 1=川, 2=小, 3=将}
遍历Map
使用forEach遍历
val mMap = mutableMapOf(0 to "秦", 1 to "川", 2 to "小", 3 to "将")
mMap.entries.forEach {
print("" + it.key + "\t" + it.value + "\n")
}
打印输出:
0 秦
1 川
2 小
3 将