코틀린 문법 - Collection(1) types

kimgwon·2024년 10월 7일

Kotlin

목록 보기
3/19

컬렉션 타입은 두 개의 인터페이스로 표현된다.

  • read-only : 컬렉션 요소에 접근할 수 있는 기능 제공
  • mutable : read-only에서 확장하여 요소 추가, 제거, 업데이트 같은 쓰기 작업을 제공

변경 가능한 컬렉션은 var로 할당할 필요는 없다. val로 할당하더라도 쓰기 작업이 가능하다.
val로 할당하는 것은 참조를 수정하지 않도록 보호하는 역할을 한다. 이는 참조가 의도치 않게 수정되는 것을 방지할 수 있다.
가능한 val을 사용하여 견고한 코드를 작성하라.


🫧 List

순서가 있는 컬렉션이다.

순서 O (요소를 인덱스로 접근할 수 있다.)
중복 O

  • MutableList (mutable) : 요소 추가, 제거, 업데이트 가능

✏️ 생성

val emptyList1 = listOf()
val emptyList2 = listOf<Int>()
val repeated = List(3) { "Kotlin" } // 3번 반복: ["Kotlin", "Kotlin", "Kotlin"]
val numbers = listOf(1, 2, 3, 4, 5) // 읽기 전용 리스트

val emptyMutableList1 = mutableListOf()
val emptyMutableList2 = mutableListOf<Int>()
val mutableRepeated = MutableList(3) { "Kotlin" } // 3번 반복: ["Kotlin", "Kotlin", "Kotlin"]
val mutableNumbers = mutableListOf(1, 2, 3, 4)      // 변경 가능한 리스트

🫧 Set

중복 요소가 없는 컬렉션이다.
순서 X
중복 X

  • MutableSet (mutable) : 요소 추가, 제거, 업데이트 가능

✏️ 생성

val emptySet = setOf<Double>()
val set = setOf(1, 2, 3)

val mutableEmptySet = mutableSetOf<Boolean>()
val mutableSet = mutableSetOf(1, 2, 3)

✏️ 합집합 : union, +

List로도 가능하나, 결과는 Set으로 반환된다.

val numbers = setOf("one", "two", "three")
println(numbers union setOf("four", "five"))    // [one, two, three, four, five]
println(setOf("four", "five") union numbers)    // [four, five, one, two, three]

✏️ 교집합 : intersect, &

List로도 가능하나, 결과는 Set으로 반환된다.

val numbers = setOf("one", "two", "three")
println(numbers intersect setOf("two", "one"))  // [one, two]

✏️ 차집합 : subtract, -

List로도 가능하나, 결과는 Set으로 반환된다.

val numbers = setOf("one", "two", "three")
println(numbers subtract setOf("three", "four"))  // [one, two]

🫧 Map

키-값 쌍으로 이루어진 컬렉션이다. 키는 고유해야 하지만, 값은 중복될 수 있다.
순서 X
중복 X

  • MutableMap (mutable) : 요소 추가, 제거, 업데이트 가능

✏️ 생성

val emptyMap = mapOf<String, Int>()
val map = mapOf("A" to 1, "B" to 2, "C" to 3)

val mutableEmptyMap2 = mutableMapOf<String, String>()
val mutableMap = mutableMapOf("A" to 1, "B" to 2, "C" to 3)

✏️ 키와 값 조회 : get(), []

val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap.get("one"))                // 1
println(numbersMap["one"])                    // 1
println(numbersMap.getOrDefault("four", 10))  // 10
println(numbersMap["five"])                   // null
// numbersMap.getValue("six")                // 예외 발생!

val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap.keys)     // [one, two, three]
println(numbersMap.values)   // [1, 2, 3]

✏️ 필터링 : filter(), filterKeys(), filterValues()

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10 }
println(filteredMap)  // {key11=11}

val filteredKeysMap = numbersMap.filterKeys { it.endsWith("1") }
val filteredValuesMap = numbersMap.filterValues { it < 10 }
println(filteredKeysMap)    // {key1=1, key11=11}
println(filteredValuesMap)  // {key1=1, key2=2, key3=3}

✏️ 값 추가 : +, [], put(), putAll()

val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap + Pair("four", 4))  // {one=1, two=2, three=3, four=4}
println(numbersMap + Pair("one", 10))  // {one=10, two=2, three=3}
println(numbersMap + mapOf("five" to 5, "one" to 11))  // {one=11, two=2, three=3, five=5}
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap["three"] = 3
numbersMap.put("four", 4)
println(numbersMap)  // {one=1, two=2, three=3, four=4}

✏️ 값 삭제 : -, remove()

val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap - "one")              // {two=2, three=3}
println(numbersMap - listOf("two", "four"))  // {one=1, three=3}

numbersMap.remove("one")
println(numbersMap)  // {two=2, three=3}
numbersMap.remove("three", 4)  // 삭제되지 않음

🫧 ArrayDeque (mutable)

양 끝에서 요소를 추가하거나 제거할 수 있는 이중 연결 큐이다.
순서 O
중복 O

✏️ 생성

val deque = ArrayDeque(listOf(1, 2, 3))

0개의 댓글