본문 바로가기
Android (Kotlin)/kotlin 문법

[Kotlin] Map mapOf(), mutableMapOf(), hashMapOf(), sortedMapOf(), linkedMapOf()

by 키윤 2023. 12. 6.

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
}