본문 바로가기
Kotlin

[Kotlin 강의] Map 응용 예제

by 뷰티풀스택 2025. 1. 21.
반응형

실전에서 사용할 수 있는 Map 응용 예제 모음

 

1. Basic Read-Only Map

fun main() {
    // Creating a read-only Map using `mapOf`
    val number2word: Map<Int, String> = mapOf(1 to "One", 2 to "Two", 3 to "Three")

    // Retrieving a value by key
    val n = 2
    println("$n is spelled as ${number2word[n]}")

    // Checking if a key exists in the map
    val keyToCheck = 4
    println("Does key $keyToCheck exist? ${keyToCheck in number2word}")

    // Checking if a value exists in the map
    val valueToCheck = "Three"
    println("Does value $valueToCheck exist? ${number2word.containsValue(valueToCheck)}")
}

 

 

2. Mutable Map

fun main() {
    // Creating a mutable Map using `mutableMapOf`
    val mutableNumber2word = mutableMapOf(1 to "One", 2 to "Two")

    // Adding a new key-value pair
    mutableNumber2word[3] = "Three"
    println("After adding key 3: $mutableNumber2word")

    // Modifying an existing key-value pair
    mutableNumber2word[2] = "Two - Updated"
    println("After updating key 2: $mutableNumber2word")

    // Removing a key-value pair
    mutableNumber2word.remove(1)
    println("After removing key 1: $mutableNumber2word")

    // Iterating through a map
    for ((key, value) in mutableNumber2word) {
        println("Key: $key, Value: $value")
    }
}

 

 

3. Creating Maps with Different Types

fun main() {
    // A Map where both keys and values are strings
    val capitals = mapOf(
        "USA" to "Washington D.C.",
        "France" to "Paris",
        "Japan" to "Tokyo"
    )
    println("Capitals Map: $capitals")

    // A Map with any type as a key or value
    val mixedMap: Map<Any, Any> = mapOf(
        "Age" to 30,
        100 to "Hundred",
        true to "Boolean Key"
    )
    println("Mixed Map: $mixedMap")
}

 

 

4. Filtering and Transformations

fun main() {
    val number2word = mapOf(1 to "One", 2 to "Two", 3 to "Three", 4 to "Four")

    // Filter keys
    val filteredByKey = number2word.filterKeys { it > 2 }
    println("Filtered by key (keys > 2): $filteredByKey")

    // Filter values
    val filteredByValue = number2word.filterValues { it.startsWith("T") }
    println("Filtered by value (values start with 'T'): $filteredByValue")

    // Map transformation (e.g., converting each entry to uppercase)
    val transformed = number2word.mapValues { (_, value) -> value.uppercase() }
    println("Transformed values: $transformed")
}

 

 

5. Using plus and minus Operators

fun main() {
    val baseMap = mapOf(1 to "One", 2 to "Two")

    // `plus` operator: returns a new Map by adding new entries
    val extendedMap = baseMap + (3 to "Three")
    println("Extended Map: $extendedMap")

    // `minus` operator: returns a new Map by removing the specified keys
    val reducedMap = extendedMap - 1
    println("Reduced Map: $reducedMap")
}

 

 

6. Combining with Sets

fun main() {
    // A set of supported protocols
    val supported = setOf("HTTP", "HTTPS", "FTP")
    val requested = "smtp"

    // Checking membership with `in`
    val isSupported = requested.uppercase() in supported
    println("Support for $requested: $isSupported")

    // A map from numbers to words
    val number2word: Map<Int, String> = mapOf(1 to "One", 2 to "Two", 3 to "Three")
    val n = 2
    println("$n is spelled as ${number2word[n]}")
}

 

 

7. Safe Access with getOrDefault and getOrElse

fun main() {
    val number2word = mapOf(1 to "One", 2 to "Two")

    // Trying to get a key that doesn't exist
    val notExistKey = 3

    // getOrDefault
    println("Using getOrDefault: ${number2word.getOrDefault(notExistKey, "Unknown")}")

    // getOrElse
    println("Using getOrElse: ${number2word.getOrElse(notExistKey) { "Not Found" }}")

    // Elvis operator alternative
    println("Using Elvis operator: ${number2word[notExistKey] ?: "N/A"}")
}

 


Toy project

fun main() {
    // Step 1: Create a mutable map
    val userScores = mutableMapOf(
        "Alice" to 150,
        "Bob" to 120,
        "Charlie" to 180
    )

    // Step 2: Add/Update entries
    userScores["Dave"] = 200
    userScores["Alice"] = 160 // Updating Alice's score

    // Step 3: Filter out high scorers
    val highScorers = userScores.filterValues { it >= 150 }
    println("High Scorers: $highScorers")

    // Step 4: Add a bonus to everyone using mapValues
    val bonusScores = userScores.mapValues { (_, score) -> score + 20 }
    println("Scores after bonus: $bonusScores")

    // Step 5: Safely access a user that might not exist
    val newUser = "Eve"
    val userScore = bonusScores.getOrElse(newUser) { 0 }
    println("$newUser's score is $userScore (defaulted to 0 if not found)")

    // Step 6: Iterate and print
    for ((user, score) in bonusScores) {
        println("$user => $score")
    }
}

 

 

현업에서 유사한 상황을 만날 때만 참조해서 보면 유용할 것 같다.

반응형

댓글