Kotlin

[Kotlin] Map & Set 사용 방법

cob 2022. 9. 20. 08:34
Map이란?
key와 value를 짝지어 저장하는 Collection이다. Map의 key는 유일하기 때문에 동일한 이름의 key는 허용되지 않는다.

 

Set이란?
동일한 아이템이 없는 Collection이다. Set의 아이템들의 순서는 특별히 정해져 있지 않고, Set은 null 객체를 갖고 있을 수 있다. 동일한 객체는 추가될 수 없기 때문에 null도 1개만 갖고 있을 수 있다

 

 

1. Map

// 읽기 전용
val readMap = mapOf("name" to "junsu", "age" to 13, "age" to 15, "height" to 160)
println(readMap) // {name=junsu, age=15, height=160} 중복 불가

val mutableMap = mutalbeMapOf("돈까스" to "일식", "짜장면" to "중식", "김치" to "중식")
mutableMap.put("막국수","한식")    // 새로운 요소 추가 -> null
mutableMap.remove("돈가스")        // key값으로 요소 삭제 -> 일식
mutableMap.repalce("김치", "한식") // 기존 요소 교체 -> 중식
println(mutableMap)               // {짜장면=중식, 김치=한식, 막국수=한식}
  • mapOf : 읽기만 가능
  • mutableMap : 읽고, 쓰기 가능

 

 

 

 


2. Set

// 읽기 전용 셋
val readSet = setOf(1,1,2,2,2,3,3)
println(readSet) // [1,2,3]

// 읽기 쓰기 모두 가능한 셋
val mutableSet = mutableSetOf(1,2,3,3,3,3)
mutableSet.add(100)    // 100 추가 -> true
mutableSet.remove(1)   // 1 제거 -> true
mutableSet.remove(200) // 200 제거 -> false

println(mutableSet)    // [2, 3, 100]
mutableSet.contains(1) // 1을 제거했기 때문에 false
  • setOf : 읽기만 가능
  • mutableSetOf : 읽고, 쓰기 가능
반응형