코틀린 문법 - Collections(3) transformation operations

kimgwon·2024년 10월 7일

Kotlin

목록 보기
5/19

map

  • map(): 각 요소에 함수를 적용하여 변환된 리스트 반환
  • mapIndexed(): 인덱스와 함께 요소를 사용해 변환
  • mapNotNull(): null이 반환되면 해당 요소를 필터링
  • mapIndexedNotNull(): 인덱스와 함께 null을 필터링하며 변환
val numbers = setOf(1, 2, 3)
println(numbers.map { it * 3 }) // [3, 6, 9]
println(numbers.mapIndexed { idx, value -> value * idx }) // [0, 2, 6]

println(numbers.mapNotNull { if (it == 2) null else it * 3 }) // [3, 9]
println(numbers.mapIndexedNotNull { idx, value -> if (idx == 0) null else value * idx }) // [2, 6]
  • mapKeys(): Key만 변환
  • mapValues(): Value만 변환
val numbersMap = mapOf("key1" to 1, "key2" to 2)
println(numbersMap.mapKeys { it.key.uppercase() }) // {KEY1=1, KEY2=2}
println(numbersMap.mapValues { it.value * 2 }) // {key1=2, key2=4}

zip

두 컬렉션의 동일한 위치에 있는 요소들을 쌍으로 묶어 Pari 객체 리스트를 생성
컬렉션의 크기가 다를 경우, 더 작은 컬렉션의 크기만큼 결과 생성

  • upzip(): Pair을 두 개의 리스트로 나눌 수 있음
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
println(colors zip animals) // [(red, fox), (brown, bear), (grey, wolf)]

val numberPairs = listOf("one" to 1, "two" to 2)
println(numberPairs.unzip()) // ([one, two], [1, 2])

flatten & flatMap

  • flatten(): 중첩된 컬렉션을 단일 리스트로 평탄화
  • flatMap(): 각 요소에 맵핑된 결과를 평탄화
val numberSets = listOf(setOf(1, 2), setOf(3, 4))
println(numberSets.flatten()) // [1, 2, 3, 4]

val containers = listOf(
    listOf("one", "two"),
    listOf("three", "four")
)
println(containers.flatMap { it }) // [one, two, three, four]

String Representation

  • joinToString(): default는 , 로 구분된 문자열을 반환한다.
  • joinTo(): 인자로 주어진 객체 뒤에 덧붙인다.
val numbers = listOf("one", "two", "three")
println(numbers.joinToString()) // one, two, three

println(numbers.joinToString { "Number: $it" })
// Number: 1, Number: 2, Number: 3, ...

val listString = StringBuffer("The list of numbers: ")
numbers.joinTo(listString)
println(listString)
// The list of numbers: one, two, three, four

0개의 댓글