Kotlin Map 사용법

: ) YOUNG·2022년 7월 8일
1

자료구조

목록 보기
3/6

생성


map은 간단하게 key 와 value로 이루어진 자료구조입니다.
key는 중복될 수 없지만, value는 중복될 수 있습니다.

키와 값 넣기

방법 1


    val map = HashMap<Int, String>()
    map.put(12, "a")
    map.put(13, "a")
    map.put(14, "a")
    map.put(15, "a")

방법 2


    val map = HashMap<Int, String>()
    map[12] = "a"
    map[13] = "a"
    map[14] = "a"
    map[15] = "a"

2가지 방법은 약간의 차이가 있지만, 방법만 다를 뿐 결과는 같습니다.



출력



forEach 사용

가장 간단한 방법입니다.


    val map = LinkedHashMap<Int, String>()
    map.put(31, "c")
    map.put(12, "b")
    map.put(77, "a")
    
    // key만 출력
    map.forEach {println(it.key)}

    // value만 출력
    map.forEach{ println(it.value)}

    // 모두 출력
    map.forEach{ println("${it.key}, ${it.value}")}

출력


31
12
77

c
b
a

31, c
12, b
77, a

entries 사용


    val map = LinkedHashMap<Int, String>()
    map.put(31, "c")
    map.put(12, "b")
    map.put(77, "a")

    val ent = map.entries
    println(ent)

출력

[31=c, 12=b, 77=a]

Iterator 사용


    val map = LinkedHashMap<Int, String>()
    map.put(31, "c")
    map.put(12, "b")
    map.put(77, "a")

    val iter : Iterator<Map.Entry<Int, String>> = map.entries.iterator()
    while(iter.hasNext()) {
        var entrySet = iter.next()
        println("${entrySet.key}, ${entrySet.value}")
    }

출력

31, c
12, b
77, a

저는 Iterator를 Map을 사용할 때 가장 많이 사용하는 방법입니다.
이유는 특정 Key값을 통해 value를 찾아야 하거나 특정 value를 통해 Key값을 찾을 때 아주 유용한 방법이기 때문입니다.

예시를 한번 보겠습니다.
map에서 "c" value의 key값을 찾아야 하는 상황이라면


    val iter : Iterator<Map.Entry<Int, String>> = map.entries.iterator()
    while(iter.hasNext()) {
        var entrySet = iter.next()
        if(entrySet.value.equals("c")) println(entrySet.key)
    }
    
   

출력

31

알고리즘 문제를 풀 때 위와 같은 상황이 생길경우 Iterator는 좋은 해결방법이 될 수 있습니다.

하지만, Iterator는 휘발성이기 때문에 마지 StringTokenizer 처럼 모든 next() 값이 나올 경우 새로 Iterator를 생성해야 한다는 치명적인 단점이 있습니다.

본인의 입맛에 따라 잘 선택하셔서 사용하시면 될 것 같습니다.



정렬



key를 기준으로 정렬


import java.util.*
import kotlin.collections.LinkedHashMap

fun main() {
    val map = LinkedHashMap<Int, String>()
    map.put(31, "c")
    map.put(12, "b")
    map.put(77, "a")
    println(map)

    val sortdedMap = sortMapByValue(map)
    print(sortdedMap)
} // End of main

private fun sortMapByValue(map : Map<Int, String>) : LinkedHashMap<Int, String> {
    val ent = LinkedList(map.entries)
    ent.sortBy { it.value }

    val result = LinkedHashMap<Int, String>()
    for(e in ent) {
        result.put(e.key, e.value)
    }

    return result
} // End of sortMapByValue

value를 기준으로 정렬


import java.util.*
import kotlin.collections.LinkedHashMap

fun main() {
    val map = LinkedHashMap<Int, String>()
    map.put(31, "c")
    map.put(12, "b")
    map.put(77, "a")
    println(map)

    val sortdedMap = sortMapByValue(map)
    print(sortdedMap)
} // End of main

private fun sortMapByValue(map : Map<Int, String>) : LinkedHashMap<Int, String> {
    val ent = LinkedList(map.entries)
    ent.sortBy { it.value }

    val result = LinkedHashMap<Int, String>()
    for(e in ent) {
        result.put(e.key, e.value)
    }

    return result
} // End of sortMapByValue

메커니즘은 간단합니다. 그냥 map의 entry를 LinkedList에 집어 넣어

LinkedList를 정렬하는 방식으로 합니다. 여기서 key값과 value를 지정하는 것은 LinkedList에서 sort.By 메소드를 활용해서 it.key로 할지 it.value로 할지만 정해주면 됩니다.

둘의 코드도 큰 차이점이 없습니다.



0개의 댓글