Hanbit the Developer
Kotlin Documentation | Map-specific operations 본문
Category: Standard library - Collections
문서 링크: https://kotlinlang.org/docs/map-operations.html
Retrieve keys and values
- get(), this[key]: 찾을 수 없는 경우 null을 반환한다.
- getOrElse(), getOrDefault()
- getValue(): 찾을 수 없는 경우 예외를 던진다.
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap.get("one"))
println(numbersMap["one"])
println(numbersMap.getOrDefault("four", 10))
println(numbersMap["five"]) // null
//numbersMap.getValue("six") // exception!
1
1
10
null
- this.keys, this.values
Filter
- filter()
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
- filterKeys()
- filterValues()
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredKeysMap = numbersMap.filterKeys { it.endsWith("1") }
val filteredValuesMap = numbersMap.filterValues { it < 10 }
Plus and minus operators
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap + Pair("four", 4))
println(numbersMap + Pair("one", 10))
println(numbersMap + mapOf("five" to 5, "one" to 11))
{one=1, two=2, three=3, four=4}
{one=10, two=2, three=3}
{one=11, two=2, three=3, five=5}
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap - "one")
println(numbersMap - listOf("two", "four"))
{two=2, three=3}
{one=1, three=3}
Map write operations
Rules:
- key는 변경할 수 없으며, value는 변경할 수 있다.
- key-value는 한 쌍이다.(a single value associated with the key)
Add and update entries
- put(), putAll(): key가 이미 있는 경우 덮어쓴다.
numbersMap.put("three", 3)
numbersMap.putAll(setOf("four" to 4, "five" to 5))
- plusAssign(), +=
- this[], set()
Remove entries
- remove()
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap.remove("one")
numbersMap.remove("three", 4) //doesn't remove anything
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "threeAgain" to 3)
numbersMap.keys.remove("one")
println(numbersMap)
numbersMap.values.remove(3)
println(numbersMap)
- minusAssign(), -=
'Kotlin' 카테고리의 다른 글
Kotlin Documentation | Opt-in requirements (0) | 2023.05.24 |
---|---|
Kotlin Documentation | Scope functions (0) | 2023.05.24 |
Kotlin Documentation | Set-specific operations (0) | 2023.05.24 |
Kotlin Documentation | List-specific operations (0) | 2023.05.24 |
Kotlin Documentation | Write operations (0) | 2023.05.24 |