PHpullh
학습 라이브러리/Kotlin/맵 조작 심화 (Map Operations)

KOTLIN · 컬렉션

맵 조작 심화 (Map Operations)

맵의 변환, 병합, 필터링 등 고급 연산을 다룹니다. getOrDefault, merge, mapValues를 활용합니다.

컬렉션중급mapgetOrPutmapValuesgroupingBymerge

핵심 설명

맵의 변환, 병합, 필터링 등 고급 연산을 다룹니다. getOrDefault, merge, mapValues를 활용합니다.

Kotlin code

fun main() {
    val scores = mutableMapOf("국어" to 85, "수학" to 92, "영어" to 78)

    // getOrDefault / getOrPut
    println(scores.getOrDefault("과학", 0))  // 0
    scores.getOrPut("과학") { 88 }
    println(scores["과학"])  // 88

    // mapValues / mapKeys
    val grades = scores.mapValues { (_, score) ->
        when {
            score >= 90 -> "A"
            score >= 80 -> "B"
            else -> "C"
        }
    }
    println(grades)

    // 맵 병합
    val map1 = mapOf("a" to 1, "b" to 2)
    val map2 = mapOf("b" to 3, "c" to 4)
    val merged = map1 + map2  // map2가 우선
    println(merged)  // {a=1, b=3, c=4}

    // filterKeys / filterValues
    val passed = scores.filterValues { it >= 80 }
    println("합격: $passed")

    // 단어 빈도 수 세기
    val words = "the cat sat on the mat the cat".split(" ")
    val freq = words.groupingBy { it }.eachCount()
    println(freq)
}

학습 팁

groupingBy { }.eachCount()는 빈도수 세기의 관용적 패턴입니다. fold보다 간결합니다.

주의할 점

맵의 + 연산은 키가 중복되면 오른쪽 값이 우선합니다. 값을 병합하려면 merge 함수를 사용하세요.

자주 묻는 질문

맵 조작 심화 (Map Operations)란 무엇인가요?

맵의 변환, 병합, 필터링 등 고급 연산을 다룹니다. getOrDefault , merge , mapValues 를 활용합니다.

맵 조작 심화 (Map Operations) 학습 시 주의할 점은 무엇인가요?

맵의 + 연산은 키가 중복되면 오른쪽 값이 우선합니다. 값을 병합하려면 merge 함수를 사용하세요.