본문 바로가기

Kotlin

[Kotlin] 기본 문법 (3)

* 기본 문법 - Collections

ref: kotlinlang.com

  • Immutable: 읽기 전용 컬렉션이다.
  • Mutable: 삽입, 수정, 삭제와 같은 쓰기 작업이 가능한 컬렉션이다.
  • List, Set, Map은 기본적으로 Immutable 객체이다.
  • ListOf<typeName>(Items...), SetOf<typeName>(Items...), MapOf<typeName>(Items...)로 생성할 수 있다. 이때, typeName은 생략 가능하다.
 val immutableList = listOf("달러", "유로", "원")
 val immutableSet = setOf("달러", "유로", "원")
 val immutableMap = mapOf("one" to 1, "two" to 2, "three" to 3)
  • Collection Builder을 사용하여 Immutable 객체를 생성할 수 있다.
val buildList: List<Int> = buildList {
    add(1)
    add(2)
    add(3)
}

val buildSet: Set<Int> = buildSet {
    add(1)
    add(2)
    add(3)
}

val buildMap: Map<String, Int> = buildMap {
    put("one", 1)
    put("two", 2)
    put("three", 3)
}
  • MutableList, MutableSet, MutableMap은 Mutable 객체이다.
  • mutableListOf<typeName>(), mutableSetOf<typeName>(), mutableMapOf<typeName>()로 생성할 수 있다.
val mutableList = mutableListOf<String>("one", "two", "three")

val mutableSet = mutableSetOf<String>("one", "two", "three")

val mutableMap = mutableMapOf<String, Int>("one" to 1, "two" to 2, "three" to 3)
  • ArrayList, LinkedList 등 다양한 Collection을 사용할 수 있다.
val arrayList = ArrayList<Int>().apply {
    add(1)
    add(2)
    add(3)
    add(4)
}

val linkedList = LinkedList<Int>().apply {
    add(1)
    add(2)
    add(3)
    addFirst(0)
    add(4)
    addLast(5)
}

* 기본 문법 - Stream

  • Java와 마찬가지로 filter, map 등 다양한 함수를 제공한다.
val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val evenList =  numberList.filter { it % 2 == 0 }

val lowerList = listOf("a", "b", "c")
val upperList = lowerList.map { it.uppercase() }
  • .collect(Collectors.toList())와 같은 terminal Operator가 존재하지 않는다.
  • filter {}, map {} 등의 함수가 실행될 때마다 자동으로 새로운 Stream을 생성하기 때문에 다중 filter, map 처리 시 메모리 낭비가 발생할 수 있다.
  • Java의 Stream과 달리 Lazy Evaluation이 아닌 Eager Evaluation으로 동작한다.
  • 인라인 함수를 사용하기 때문에 객체를 생성해서 저장한다는 오버헤드는 없지만 실행마다 stream을 생성하기 때문에 오버헤드가 발생한다.
  • stream()를 사용하면 Lazy Evaluation으로 동작한다.
val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val evenList =  numberList.stream().filter {
    it % 2 == 0
}

* 기본 문법 - asSequence

  • asSequence는 Stream과 다르게 Lazy Evaluation으로 동작한다.
  • terminal Operator이 필요하다.
val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val oddList =  numberList.asSequence().filter { it % 2 == 1 }.toList()
  • asSequence()는 인라인 함수가 아니기 때문에 중첩으로 사용하면 객체를 생성하는 오버헤드가 발생한다.
  • Collection의 요소가 적을 때는 객체를 생성하는 오버헤드가 더 크고, 요소가 많을 때는 Stream을 생성하는 오버헤드가 더 크므로, asSequence()는 Collection의 요소가 많을 때 사용하는 것이 좋다.

'Kotlin' 카테고리의 다른 글

[Kotlin] 범위 지정 함수  (0) 2023.03.23
[Kotlin] 기본 문법 (4)  (0) 2022.10.28
[Kotlin] 기본 문법 (2)  (0) 2022.10.25
[Kotlin] 기본 문법 (1)  (0) 2022.10.23
[Kotlin] Kotlin이란?  (0) 2022.10.21