Search

Map-specific operations

Map에서는 Key와 Value의 타입을 사용자가 정의한다.
Key를 기반으로 한 Map 항목에 대한 접근은 Key로 Value를 가져오는 것부터 Key와 Value를 각각 필터링하는 것까지 다양한 Map 특정 처리 기능을 제공한다.

Key와 Value 조회

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") // 예외 발생!
Kotlin
복사
Map에서 Value를 조회하려면 get() 함수의 인수로 Key를 제공해야 한다.
축약형으로 [key] 문법도 지원된다.
만약 제공된 Key가 존재하지 않으면 null을 반환한다.
또한 getValue()라는 함수도 있는데 이 함수는 Key가 Map에 존재하지 않으면 예외를 발생시킨다.
Key가 없을 때 추가적인 처리를 하는 두 가지 방법이 존재한다.
getOrElse()
존재하지 않는 Key에 대한 Value는 제공된 람다 함수로부터 반환된다.
getOrDefault()
Key가 없을 때 지정된 기본값을 반환한다.
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3) println(numbersMap.keys) println(numbersMap.values)
Kotlin
복사
Map의 모든 Key 또는 Value를 대상으로 작업하려면 keys 와 values 속성에서 이를 가져올 수 있다.
keys는 모든 Map의 Key들이며 values는 모든 Map의 Value들의 모음이다.

필터링

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 } println(filteredMap)
Kotlin
복사
Map도 다른 컬렉션처럼 filter() 함수를 사용하여 필터링 할 수 있다.
Map에 filter() 를 호출할 때는 Pair 를 인수로 받는 조건자를 전달한다.
이로 인해 필터링 조건자에서 Key와 Value를 모두 사용할 수 있다.
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 } println(filteredKeysMap) println(filteredValuesMap)
Kotlin
복사
Map을 필터링하는 두 가지 특정 방법이 존재한다.
filterKeys()
Key만 검사하는 조건자를 통해 Key로 Map을 필터링하는 방법
filterValues()
Value만 검사하는 조건자를 통해 Value로 Map을 필터링하는 방법

플러스와 마이너스 연산자

Map 요소에 대한 Key 접근 때문에 +- 연산자는 다른 컬렉션과는 다르게 동작한다.
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))
Kotlin
복사
+ 는 왼쪽의 Map과 오른쪽의 Pair 또는 다른 Map을 합친 요소를 포함하는 Map을 반환한다.
오른쪽 피연산자가 왼쪽 Map에 이미 존재하는 Key를 포함하는 경우 결과 Map에는 오른쪽 항목이 포함된다.
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3) println(numbersMap - "one") println(numbersMap - listOf("two", "four"))
Kotlin
복사
- 는 왼쪽 Map의 항목에서 오른쪽 피연산자에 있는 Key들을 제외한 Map을 생성한다.
오른쪽 피연산자는 단일 Key 또는 Key들의 컬렉션이 될 수 있다.

맵 쓰기 작업

Map에 쓰기 작업 규칙
Value는 업데이트할 수 있지만 Key는 변하지 않는다. (한 번 항목을 추가하면 해당 Key는 고정된다.)
각 Key에는 항상 단일 Value가 연결되며 전체 항목을 추가하거나 제거할 수 있다.

추가 및 업데이트

val numbersMap = mutableMapOf("one" to 1, "two" to 2) numbersMap.put("three", 3) println(numbersMap)
Kotlin
복사
새로운 Key-Value 쌍을 변경 가능한 Map에 추가하려면 put() 함수를 사용한다.
새로운 항목이 LinkedHashMap(기본 Map 구현)에 추가되면 순회할 때 마지막에 나타난다.
정렬된 Map에서는 새로운 요소들의 위치가 Key의 순서에 의해 정의된다.
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3) numbersMap.putAll(setOf("four" to 4, "five" to 5)) println(numbersMap)
Kotlin
복사
한 번에 여러 항목을 추가하려면 putAll() 함수를 사용하라.
이 함수의 인수는 Map이나 Pair 그룹(Iterable, Sequence 또는 Array)일 수 있다.
val numbersMap = mutableMapOf("one" to 1, "two" to 2) val previousValue = numbersMap.put("one", 11) println("value associated with 'one', before: $previousValue, after: ${numbersMap["one"]}") println(numbersMap)
Kotlin
복사
put() 과 putAll() 은 지정된 Key가 이미 존재할 경우 Value를 덮어쓴다.
따라서 이 함수들을 사용하여 Map 항목의 값을 업데이트할 수 있다.
val numbersMap = mutableMapOf("one" to 1, "two" to 2) numbersMap["three"] = 3 // numbersMap.put("three", 3) 호출 numbersMap += mapOf("four" to 4, "five" to 5) println(numbersMap)
Kotlin
복사
새 항목을 추가하는 또 다른 방법으로는 두 가지 방법의 연산자 표기법이 있다.
+= (plusAssign) 연산자
[] 연산자

제거

val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3) numbersMap.remove("one") println(numbersMap) numbersMap.remove("three", 4) // 아무것도 제거하지 않음 println(numbersMap)
Kotlin
복사
변경 가능한 Map에서 항목을 제거하려면 remove() 함수를 사용하라.
remove() 함수를 호출할 때는 Key 또는 전체 Key-Value 쌍을 전달할 수 있다.
Key와 Value 둘 다 지정하면 Value가 일치할 때만 해당 Key가 제거된다.
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)
Kotlin
복사
Key나 Value로 항목을 제거할 수도 있다.
이를 위해 Map의 keysvalues 에서 remove() 를 호출하고 제거할 Key나 Value를 제공하면 된다.
values 에서 호출하면 주어진 Value와 일치하는 첫 번째 항목만 제거한다.
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3) numbersMap -= "two" println(numbersMap) numbersMap -= "five" // 아무것도 제거하지 않음 println(numbersMap)
Kotlin
복사
-= (minusAssign) 연산자도 변경 가능한 Map에서 사용할 수 있다.