PHpullh
학습 라이브러리/Kotlin/associate 변환 심화

KOTLIN · 컬렉션

associate 변환 심화

associateWith, associateBy 등 다양한 맵 변환 함수를 활용합니다.

컬렉션중급associateWithassociateBymapTransformgroupBy

핵심 설명

associateWith, associateBy 등 다양한 맵 변환 함수를 활용합니다.

Kotlin code

data class Product(val id: Int, val name: String, val category: String, val price: Int)

fun main() {
    val products = listOf(
        Product(1, "노트북", "전자기기", 1500000),
        Product(2, "마우스", "전자기기", 30000),
        Product(3, "펜", "문구", 3000),
        Product(4, "노트", "문구", 5000),
    )

    // associateBy: 특정 키로 맵 생성
    val byId = products.associateBy { it.id }
    println("ID 2: ${byId[2]?.name}")

    // associateWith: 값을 변환
    val names = listOf("kotlin", "java", "python")
    val lengths = names.associateWith { it.length }
    println(lengths) // {kotlin=6, java=4, python=6}

    // associate: 키-값 쌍 직접 지정
    val priceMap = products.associate { it.name to it.price }
    println(priceMap)

    // groupBy + mapValues 조합
    val categoryAvg = products
        .groupBy { it.category }
        .mapValues { (_, prods) -> prods.map { it.price }.average() }
    println("카테고리별 평균: $categoryAvg")
}

학습 팁

associateWith는 원소 자체가 키가 되고 변환 결과가 값이 됩니다. 역방향인 associateBy와 구분하세요.

주의할 점

associateBy에서 키가 중복되면 마지막 원소만 남습니다. 중복 가능성이 있으면 groupBy를 사용하세요.

자주 묻는 질문

associate 변환 심화란 무엇인가요?

associateWith , associateBy 등 다양한 맵 변환 함수를 활용합니다.

associate 변환 심화 학습 시 주의할 점은 무엇인가요?

associateBy 에서 키가 중복되면 마지막 원소만 남습니다. 중복 가능성이 있으면 groupBy 를 사용하세요.