1. mapOf()
val mapWithValues = mapOf("Key1" to "Value1", "Key2" to "Value2", "Key3" to "Value3")
val mapWithoutValues = mapOf<String, String>()
val emptyMap = emptyMap<String, String>()
2. mutableMapOf()
val emptyMutableMap = mutableMapOf<String, String>()
emptyMutableMap["Key"] = "Value"
val mutableMap = mutableMapOf("Key1" to "Value1", "Key2" to "Value2", "Key3" to "Value3")
mutableMap["Key3"] = "Value10" // modify value
mutableMap["Key4"] = "Value4" // add value
mutableMap.remove("Key1") // delete existing value
3. hashMapOf()
hashMap은 mutableMap의 한 종류일 뿐이다.
val claims: mutableMap<String, Any> = HashMap()
// HashMap is mutable.
val hashMap = hashMapOf("Key1" to "Value1", "Key2" to "Value2", "Key3" to "Value3")
hashMap["Key3"] = "Value10" // modify entry
hashMap["Key4"] = "Value4" // add entry
hashMap.remove("Key1") // delete existing value
4. Using sortedMapOf and linkedMapOf
val sortedMap = sortedMapOf("Key3" to "Value3", "Key1" to "Value1", "Key2" to "Value2")
// creates a mutable SortedMap
val linkedMap = linkedMapOf("Key3" to "Value3", "Key1" to "Value1", "Key2" to "Value2")
// linkedMapOf function creates a LinkedMap object
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-sorted-map.html
import kotlin.test.*
import java.util.*
fun main(args: Array<String>) {
//sampleStart
val map: LinkedHashMap<Int, String> = linkedMapOf(1 to "x", 2 to "y", -1 to "zz")
println(map) // {1=x, 2=y, -1=zz}
//sampleEnd
}
'Android (Kotlin) > kotlin 문법' 카테고리의 다른 글
EditText Input Type 모두 모음 (0) | 2023.12.19 |
---|---|
동적 메모리 할당 (Dynamic Allocation) | 스택(Stack) vs 힙(Heap) (0) | 2023.12.12 |
[Kotlin] 유용한 기능 (1) | 2023.12.04 |
[Kotlin] List - forEach (2) | 2023.12.04 |
[Kotlin] abstract vs interface (1) | 2023.12.03 |