[Kotlin] Collections 알아보기

moKo·2021년 9월 15일
0

Kotlin

목록 보기
1/2

💡 Collection이란?

collections는 List, set, map등으로 구성된 자료구조로 다수의 객체를 효율적으로 관리하기 위해 사용하는 모음정도로 생각하면 될것같다.

코틀린에서의 collections은 위 사진처럼 구성되어있다.
자바에서와는 다르게 Mutable과 immutable로 나뉘는데,
Mutable은 변할 수 있고 immutable은 불변이다.
값의 성격에 따라 사용하는게 달라진다

Collection을 왜 쓸까?

collections을 사용하는 이유는 크게 3가지가 있다.

1. 일관된 API
-> Collection의 일관된 API를 사용하여 Collection 밑에 있는 모든 클래스(ArrayList, Vector, LinkedList 등) Collection에서 상속받아 통일된 메서드를 사용하게 된다

2. 프로그래밍 노력 감소
-> 객체 지향 프로그래밍의 추상화의 기본 개념이 성공적으로 구현되어있다

3. 속도 및 품질의 향상
-> 유용한 데이터 구조 및 알고리즘은 성능을 향상시킬 수 있다. Collection을 사용하여 최상의 구현을 생각할 필요없이 간단하게 Collection API를 사용하여 구현을 하면 된다.

(참고 : https://crazykim2.tistory.com/557)

이제 Collections를 자세히 알아보도록하자

List

List는 데이터가 저장하거나 삭제될 때 순서를 지키는 Collection이다.
List는 Mutable과 Immutable을 모두 지원한다.

ImmutableList (불변)

listof(item)으로 생성과 초기화를 할 수 있다. 코틀린에선 타입추론을 해주기 때문에 생략이 가능하다. immutable에선 get만 가능하다.

val fruits= listOf<String>("apple", "banana", "kiwi", "peach")
// val fruits= listOf("apple", "banana", "kiwi", "peach") -> 타입 생략 가능
println("fruits.size: ${fruits.size}")
println("fruits.get(2): ${fruits.get(2)}")
println("fruits[3]: ${fruits[3]}")
println("fruits.indexOf(\"peach\"): ${fruits.indexOf("peach")}")

실행한 결과

fruits.size: 4
fruits.get(2): kiwi
fruits[3]: peach
fruits.indexOf("peach"): 3

Mutable (가변)

mutable은 선언할때 mutableListof(item) 형식으로 선언한다.
삭제와 추가가 가능하다

val fruits= mutableListOf<String>("apple", "banana", "kiwi", "peach")
fruits.remove("apple")
fruits.add("grape")
println("fruits: $fruits")

fruits.addAll(listOf("melon", "cherry"))
println("fruits: $fruits")
fruits.removeAt(3)
println("fruits: $fruits")

실행한 결과

fruits: [banana, kiwi, peach, grape]
fruits: [banana, kiwi, peach, grape, melon, cherry]
fruits: [banana, kiwi, peach, melon, cherry]

이 외에도 replace, replaceAll, contains, forEach등의 메소드도 지원한다.

Set

Immutable (불변)

setof(items) 로 생성할 수 있다.

val numbers = setOf<Int>(33, 22, 11, 1, 22, 3)
println(numbers)
println("numbers.size: ${numbers.size}")
println("numbers.contains(1): ${numbers.contains(1)}")
println("numbers.isEmpty(): ${numbers.isEmpty()}")

실행한 결과

[33, 22, 11, 1, 3]
numbers.size: 5
numbers.contains(1): true
numbers.isEmpty(): false

Mutable (가변)

Mutable은 mutableSetOf(items)로 생성한다.

val numbers = mutableSetOf<Int>(33, 22, 11, 1, 22, 3)
println(numbers)
numbers.add(100)
numbers.remove(33)
println(numbers)

실행한 결과

[33, 22, 11, 1, 3]
[22, 11, 1, 3, 100]

Map

key와 value를 짝지어 저장하는 collection이다. key는 유일하기에 중복이 허용되지 않는다.

Immutable (불변)

mapOf<key, value> 로 생성할 수 있다.
pair객체로 아이템을 표현하며 pair에 key와 value를 넣을 수 있다.
pair(A, B)는 A to B로 표현이 가능하고 이게 가능한 것은 to가 infix 이기 때문이다.

val numbersMap = mapOf<String, String>(
  "1" to "one", "2" to "two", "3" to "three")
println("numbersMap: $numbersMap")
val numbersMap2 = mapOf(Pair("1", "one"), Pair("2", "two"), Pair("3", "three"))
println("numbersMap2: $numbersMap2")

// 실행해보면 모두 동일한 값을 갖고 있다.
// numbersMap: {1=one, 2=two, 3=three}
// numbersMap2: {1=one, 2=two, 3=three}

또한 getter는 get(index)와 [index]를 모두 지원한다.

val numbersMap = mapOf<String, String>(
  "1" to "one", "2" to "two", "3" to "three")
println("numbersMap.get(\"1\"): ${numbersMap.get("1")}")
println("numbersMap[\"1\"]: ${numbersMap["1"]}")
println("numbersMap[\"1\"]: ${numbersMap.values}")
println("numbersMap keys:${numbersMap.keys}")
println("numbersMap values:${numbersMap.values}")

for (value in numbersMap.values) {
  println(value)
}

실행한 결과

numbersMap.get("1"): one
numbersMap["1"]: one
numbersMap["1"]: [one, two, three]
numbersMap keys:[1, 2, 3]
numbersMap values:[one, two, three]
one
two
three

Mutable (가변)

Mutable은 mutableMapOf<key, value> 형식으로 생성한다
객체의 추가는 put을 사용한다.

val numbersMap = mutableMapOf<String, String>(
      "1" to "one", "2" to "two", "3" to "three")
println("numbersMap: $numbersMap")

numbersMap.put("4", "four")
numbersMap["5"] = "five"
println("numbersMap: $numbersMap")

numbersMap.remove("1")
println("numbersMap: $numbersMap")

numbersMap.clear()
println("numbersMap: $numbersMap")

실행한 결과

numbersMap: {1=one, 2=two, 3=three}
numbersMap: {1=one, 2=two, 3=three, 4=four, 5=five}
numbersMap: {2=two, 3=three, 4=four, 5=five}
numbersMap: {}

정리해본 결과 JAVA의 컬렉션과 아주 유사하고 차이점으로는 Kotlin에서는 mutable과 immutable을 지원한다는 점이 있다.

(참고 : https://codechacha.com/ko/collections-in-kotlin/)

profile
🔥 Feelings fade, results remain

0개의 댓글